3

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

1
  • 4
    The answer is Yes, but I'll let someone else answer. Weekend for me!
    – leppie
    Commented Sep 10, 2010 at 12:30

4 Answers 4

7

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

Wrong question!

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

1

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

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.