Is it possible to convert from byte [] to base64string and vice versa

I tried this:

Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")));

Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")))));

and I get different results for them, although I thought that it should be the same

+3
source share
4 answers

In the second line, you are not inverting the conversion to Base64, just re-applying it.

You want to use Convert.FromBase64String and say:

Console.WriteLine(
     Convert.ToBase64String(
        Convert.FromBase64String(
               Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")))));
+7
source

Wrong question!

You are trying to convert to base64 twice. You need to use convert from base64.

+1
source

Base64String Base64String. , Base64String .

/ :

string toEncode = "hi";

// Convert to base64string
byte[] toBytes = Encoding.UTF8.GetBytes(toEncode);
string base64 = Convert.ToBase64String(toBytes);

// Convert back from the base64string
byte[] fromBase64 = Convert.FromBase64String(base64);
string result = Encoding.UTF8.GetString(fromBase64);
+1
source

Sequence 1:

and. Convert Hello to UTF

b. Convert UTF to base 64

Sequence 2:

and. Convert hi to utf v1

b. Convert UTF v1 to base 64 v1

with. Convert base 64 v1 to UTF v2

e. Convert UTF v2 to base 64 v2

Broken down in this way, it should be clear why you do not expect them to produce the same result. Obfuscation by overlapping functional chains.

0
source

Source: https://habr.com/ru/post/1764144/


All Articles