开发者

C#:Convert.ToBase64String problem

开发者 https://www.devze.com 2023-03-17 03:41 出处:网络
I\'m new to C# development, the following code is Convert.ToBase64Stringproblem, i don\'t know how to solve it.

I'm new to C# development, the following code is Convert.ToBase64String problem, i don't know how to solve it.

 byte[] str1Byte = System.Text.Encoding.UTF8.GetBytes("xyz123");
 String plaintext = Convert.ToBase64String(str1Byte);

 byte[] plaintext_bytes = System.Text.Encoding.UTF8.GetBytes(plaintext);
 Console.WriteLine("base64 plaintext: " + plaintext);
 Console.WriteLine("plaintext_bytes to String: " + 
            开发者_Go百科       System.Text.Encoding.UTF8.GetString(plaintext_bytes));
 Console.WriteLine("ToBase64String(plaintext_bytes) : " + 
                   Convert.ToBase64String(plaintext_bytes));

Result:

base64 plaintext: eHl6MTIz 
plaintext_bytes to String: eHl6MTIz 
ToBase64String(plaintext_bytes) : ZUhsNk1USXo= 

I expect the output of "Convert.ToBase64String(plaintext_bytes))" to be "eHl6MTIz", not "ZUhsNk1USXo=".


You're trying to Base64 encode something that is already Base64 encoded:

// plaintext_bytes = eHl6MTIz 
Console.WriteLine("ToBase64String(plaintext_bytes) : " + Convert.ToBase64String(plaintext_bytes));

As mentioned, you need to go FROM base 64


it shouldnt please have look to this article Base64

Base64 isn't Ascii representation of a string


You make a confusion here: the Console.WriteLine you use will print some bytes, NOT the Base64 representation of the bytes. Base64 is a conversion algorithm, see link above. And yes, use the FromBase64String


Isn't it simply the case of you are encoding it twice?

byte[] str1Byte = System.Text.Encoding.UTF8.GetBytes("xyz123");

then

byte[] plaintext_bytes = System.Text.Encoding.UTF8.GetBytes(plaintext);

(I was a bit slow, and Chris S states it more simply)

0

精彩评论

暂无评论...
验证码 换一张
取 消