Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from byte array to base64 and back

I am trying to:

  1. Generate a byte array.
  2. Convert that byte array to base64
  3. Convert that base64 string back to a byte array.

I've tried out a few solutions, for example those in this question.

For some reason the initial and final byte arrays do not match. Here is the code used:

using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())     {          byte[] originalArray = new byte[32];          rng.GetBytes(key);          string temp_inBase64 = Convert.ToBase64String(originalArray);          byte[] temp_backToBytes = Encoding.UTF8.GetBytes(temp_inBase64);     } 

My questions are:

  1. Why do "originalArray" and "temp_backToBytes" not match? (originalArray has length of 32, temp_backToBytes has a length of 44, but their values are also different)

  2. Is it possible to convert back and forth, and if so, how do I accomplish this?

like image 516
crawfish Avatar asked Jul 24 '12 15:07

crawfish


People also ask

Is Base64 a byte array?

Now in order to save the Base64 encoded string as Image File, the Base64 encoded string is converted back to Byte Array using the Convert. FromBase64String function. Finally the Byte Array is saved to Folder on Disk as File using WriteAllBytes method of the File class.

Is Base64 and bytes same?

Each Base64 digit represents exactly 6 bits of data. So, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit Base64 digits (4×6 = 24 bits).

Is backslash allowed in Base64?

No. The Base64 alphabet includes A-Z, a-z, 0-9 and + and / . You can replace them if you don't care about portability towards other applications.


1 Answers

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64); 
like image 126
Sergey Kalinichenko Avatar answered Sep 25 '22 21:09

Sergey Kalinichenko