How to convert a byte array to a string? - c#

Using the function from: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
public static byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
As you can see it returns a byte array, I want to convert the byte array to a string.
How can I convert it from a byte array to string and visa versa?

If you don't care how it's stored, an easy way is to use:
Convert byte array into string: Convert.ToBase64String(YourByteArray) and
Convert string into byte array: Convert.FromBase64String(YourString).
This will give a concise, printable ASCII representation of the byte array.

This can help you a lot, is about to converting into Hex format but can be very usefull
How do you convert Byte Array to Hexadecimal String, and vice versa?

System.Text.Encoding.ASCII.GetString(bytes);

While using Rijndael Encryption i faced this problem, it returns encrypted byte[] (array),
Convert byte[] to string;
myStringVariable= Convert.ToBase64String(myEncryptedByteArray);
Convert string to byte[];
byte[] bytes = Convert.FromBase64String(myStringVariable);
For more about Rijndael
Cheers !!!

Related

String to HEX byte array

I like to convert String to HEX byte array.
From something like that "example" to byte[] exampleconv = {0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65} (Source: http://www.asciitohex.com/).
I search for example also on stackoverflow but most of example convert code from string to decimal byte array or similar. I didnt find any working! example to convert string to hex byte array (like exampleHEX shows above).
Use Encoding.Default.GetBytes to get byte Array. Sample code:
byte[] ba = Encoding.Default.GetBytes("example");
// jsut to Display
var hexString = BitConverter.ToString(ba);
Console.WriteLine(hexString);
You will get "65-78-61-6D-70-6C-65"
Byte arrays are stored in binary, regardless of how they are presented to the consumer.
You'll get more luck if you think about the format in which you read the array, rather than the type of numbers stored in the array.

Convert Aes.Key to SecureString in C#

How do I convert Aes.Key to a secureString ? I am doing a byte[] -> string -> securestring. I am facing a different problem.
When converting the key, in byte[], to string and back to byte[] I get a different byte[]. What is the problem with the code ?
Aes aes = Aes.Create();
aes.GenerateIV();
aes.GenerateKey();
byte[] byteKey1 = aes.Key;
string sKey = Encoding.UniCode.GetString(byteKey);
byte[] byteKey2= Encoding.UniCode.GetBytes(sKey);
"byteKey1" and "byteKey2" are sometimes different. They are equal if I use Encoding.Default but that has problems when different machines have different default encoding.
How do I convert the Key in byte[] to SecureString and back to byte[] ?
Thanks.
Never use text encoding (e.g., Unicode or ASCII) on binary data like a cryptographic key or ciphertext. Encoding is intended for textual representations, and the implementation can change the binary contents as permitted by the encoding.
Instead, use Convert.ToBase64String and Convert.FromBase64String to convert binary text into a form that can be encoded in a textual format.
The following code will illustrate byteKey2 and byteKey will be identical.
string sKey = Convert.ToBase64String(byteKey);
byte[] byteKey2= Convert.FromBase64String(sKey);
bool equal = byteKey.SequenceEqual(byteKey2); // will be true

Input string was not in a correct format?

In my application i write the code like this
byte[] byt = new byte[Convert.ToSbyte(textbox1.Text)];
it is giving the error that input string was not in a correct format.
This is a wild guess, but are you trying to convert the contents of the text box into a byte array? If so, you can do it like this:
byte[] byt = Encoding.UTF8.GetBytes(textbox1.Text);
The text in textbox1 is not a valid numeral for a signed byte.
Does it have spaces? Letters? ...?
What are you trying to do? The new byte[num] creates an array of 'num' bytes, where 'num' is usually an integer. All bytes in the array are then 0.
It doesn't create a filled array, as I suspect you may be trying to do.
What are the contents of that textbox1.Text that gave the error?
what you want in fact is this
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

String to raw byte array

I have a string which contains binary data (non-text data).
How do I convert this to a raw byte array?
A string in C# - by definition - does not contain binary data. It consists of a sequence of Unicode characters.
If your string contains only Unicode characters in the ASCII (7-bit) character set, you can use Encoding.ASCII to convert the string to bytes:
byte[] result = Encoding.ASCII.GetBytes(input);
If you have a string that contains Unicode characters in the range u0000-u00ff and want to interpret these as bytes, you can cast the characters to bytes:
byte[] result = new byte[input.Length];
for (int i = 0; i < input.Length; i++)
{
result[i] = (byte)input[i];
}
It is a very bad idea to store binary data in a string. However, if you absolutely must do so, you can convert a binary string to a byte array using the 1252 code page. Do not use code page 0 or you will lose some values when in foreign languages. It just so happens that code page 1252 properly converts all byte values from 0 to 255 to Unicode and back again.
There have been some poorly written VB6 programs that use binary strings. Unfortunately some are so many lines of code that it is almost impossible to convert it all to byte() arrays in one go.
You've been warned. Use at your own peril:
Dim bData() As Byte
Dim sData As String
'convert string binary to byte array
bData = System.Text.Encoding.GetEncoding(1252).GetBytes(sData)
'convert byte array to string binary
sData = System.Text.Encoding.GetEncoding(1252).GetString(bData)
Here is one way:
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] theBytes = encoding.GetBytes("Some String");
Note, there are other encoding formats you may want to use.

How do i compare a byte[] to string?

I want to compare the first few bytes in byte[] with a string. How can i do this?
You must know the encoding of the byte array to properly compare them.
For example, if you know your byte array is made of UTF-8 bytes, then you can create a string from the byte array:
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string s = enc.GetString(originalBytes);
Now you can compare string s to your other string.
Conversely, if you want to compare just the first few bytes, you can convert the string into a UTF8 byte array:
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
byte[] b = enc.GetBytes(originalString);
Now you can compare byte array b to your other byte array.
There are several other encoding objects for ASCII, Unicode, etc. See the MSDN page here.
use
byte [] fromString = Encoding.Default.GetBytes("helloworld");

Categories