Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert between string and byte[] without losing integrity

Tags:

c#

openid

I know how to convert from a string to byte[] in C#. In this particular case, I'm working with the string representation of an HMAC-SHA256 key. Let's say the string representation of this key I get from an OpenID OP is:

"81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8="

I convert it to byte[] like this:

byte[] myByteArr = Encoding.UTF8.GetBytes("81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=");

The problem I have with that is that it seems to be losing the original data. If I take the byte array from the previous step and convert it back to a string, it's different from the original string.

string check = Convert.ToBase64String(myByteArr);

check ends up being:

"ODFGTnliS1dmY001Mzl2Vkd0SnJYUm1vVk14Tm1aSFkzT2dVcm84K3BaOD0="

which is obviously not the same as the original string representation I started with.

like image 445
ashelvey Avatar asked May 15 '11 01:05

ashelvey


Video Answer


2 Answers

With crypto keys, always use Convert.FromBase64String and Convert.ToBase64String. That way you'll be doing it the standard way and will not lose bytes due to encoding problems. Base 64 string may not be space efficient but it is the preferred method for storage and transport of keys in many schemes.

Here is a quick verification:

byte[] myByteArr = Convert.FromBase64String("81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=");
string check = Convert.ToBase64String(myByteArr);
Console.WriteLine(check);
// Writes: 81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=
like image 58
Teoman Soygul Avatar answered Sep 19 '22 12:09

Teoman Soygul


The first function (Encoding.UTF8.GetBytes) takes a string (of any kind) and returns a byte[] that represents that string in a particular encoding -- in your case, UTF8.

The second function (Convert.ToBase64String) takes a byte array (of any kind) and returns a string in base64 format so that you can store this binary data in any ASCII-compatible field using only printable characters.

These functions are not counterparts. It looks like the string you're getting is a base64-encoded string. If this is the case, use Convert.FromBase64String to get the byte[] that it represents, not Encoding.UTF8.GetBytes.

like image 42
Adam Robinson Avatar answered Sep 18 '22 12:09

Adam Robinson