繁体   English   中英

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

[英]Encoding strings to and from base-64

我正在尝试从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;

我已经尝试过这样做,但似乎没有得到正确的结果。 我已经尝试过使用System.Text.Encoding.UnicodeSystem.Text.Encoding.UTF8

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

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

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

如果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

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

将Base64中所需的任何内容转换为Byte数组,然后使用FromBase64String和ToBase64String与Base64进行转换:

Byte[] buffer = Convert.FromBase64String(myBase64String1);
myBase64String2 = Convert.ToBase64String(buffer);

myBase64String1将等于myBase64String2。 您将需要使用其他方法将数据类型转换为Byte数组,反之则返回以获取数据类型。 我用它来将类的内容转换为字节数组,然后转换为Base64字符串并将字符串写入文件系统。 后来我通过反转过程将其读回到类实例中。

您已正确布置编码代码。 要确认base64编码的字符串是否正确,您可以尝试解码它并将解码的内容与原始字符进行比较:

var decodedBytes = Convert.FromBase64String(base64encoded);
var compareText = System.Text.Encoding.ASCII.GetString(decodedText);

if (text == compareText)
{
    // carry on...
    return base64encoded;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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