Conversion from byte array to base64 and back
C#EncodingBase64BytearrayType ConversionC# Problem Overview
I am trying to:
- Generate a byte array.
- Convert that byte array to base64
- 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:
-
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)
-
Is it possible to convert back and forth, and if so, how do I accomplish this?
C# Solutions
Solution 1 - C#
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);