将字符串编码到base-64和从base-64编码

Eri*_*son 7 c# string base64

我正在尝试从base-64字符串来回编码一些字符串,而我正在努力获得正确的结果.

string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);

if (text == base64Encoded) //If the new encoded string is equal to its original value
    return base64Encoded;
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这样做,但似乎没有得到正确的结果.我System.Text.Encoding.Unicode和两个都试过了System.Text.Encoding.UTF8

可能是什么问题呢?有没有人有适当的解决方案?

Ed *_* S. 9

string text = base64string.... //Here I have a base-64 string.
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
string base64Encoded = Convert.ToBase64String(encodedByte);
Run Code Online (Sandbox Code Playgroud)

你是对字符串进行双重编码.首先使用base64字符串,获取字节,然后再次对其进行编码.如果你想比较,你需要从原始字符串开始.

  • @ErikLarsson:好吧base64已经保证你不会丢失数据,所以我没有看到这一点.但是,如果你知道我在告诉你什么......那么问题是什么?当你一次又一次地编码一个字符串时,显然你不会得到同样的东西.从原始字符串开始,对其进行编码,如果您确实要检查则对其进行解码. (2认同)

Mar*_*ell 6

如果text是base-64字符串,那么你正在向后执行:

byte[] raw = Convert.FromBase64String(text); // unpack the base-64 to a blob
string s = Encoding.UTF8.GetString(raw); // assume the blob is UTF-8, and 
                                         // decode to a string
Run Code Online (Sandbox Code Playgroud)

这会让你成为一个string.但请注意,此方案仅对以ASCII格式表示unicode文本有用.通常,如果原始内容是,则不会对其进行base-64编码string.