簡體   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