简体   繁体   中英

is it possible to convert from byte[] to base64string and back

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

In the second line you're not inverting the conversion to Base64, just reapplying it.

You want to use Convert.FromBase64String and say:

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

Wrong question!

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

In your post, you are converting to a Base64String and then encoding that to another Base64String. That definitely isn't going to give you a result since you want to encode to a Base64String and then decode back to your original value.

Your code would have to look something like this to encode/decode:

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);

Sequence 1:

a. Convert "hi" to UTF

b. Convert UTF to base 64

Sequence 2:

a. Convert "hi" to UTF v1

b. Convert UTF v1 to base 64 v1

c. Convert base 64 v1 to UTF v2

d. Convert UTF v2 to base 64 v2

Broken down like this, it's should be clear why you would not expect these to result in the same output. Obfuscation through overlong function chaining.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM