How to convert string and byte [] without loss of integrity

I know how to convert from string to byte [] in C #. In this particular case, I am working with the string representation of the HMAC-SHA256 key. Let them say that the string representation of this key that I get from OpenID OP:

"81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8="

I convert it to byte [] as follows:

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

The problem I am facing is that it seems to be losing its original data. If I take an array of bytes from the previous step and convert it back to a string, it is different from the original string.

string check = Convert.ToBase64String(myByteArr);

check ends:

"ODFGTnliS1dmY001Mzl2Vkd0SnJYUm1vVk14Tm1aSFkzT2dVcm84K3BaOD0="

which obviously does not match the original string representation that I started with.

+5
source share
4 answers

Convert.FromBase64String Convert.ToBase64String. , - . Base 64 , .

:

byte[] myByteArr = Convert.FromBase64String("81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=");
string check = Convert.ToBase64String(myByteArr);
Console.WriteLine(check);
// Writes: 81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=
+6

(Encoding.UTF8.GetBytes) ( ) byte[], - UTF8.

(Convert.ToBase64String) ( ) base64, ASCII- , .

. , , , , base64. , Convert.FromBase64String, byte[], , Encoding.UTF8.GetBytes.

+2

, byte[] Encoding.GetBytes(string) base64, . , . base64 , . Convert.FromBase64String().

string encoded = "81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=";
byte[] decoded = Convert.FromBase64String(encoded); // this gives the bytes that the encoded string represents
+1

GetString, .

UTF8 , , .

        var original = "81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=";
        var byteArray = Encoding.UTF8.GetBytes(original);
        var copy = Encoding.UTF8.GetString(byteArray);
        bool match = (copy == original); // This returns true
+1

All Articles