2012-05-27 83 views

回答

7

在C#:

static public string EncodeTo64(string toEncode) { 
    byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); 
    string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); 
    return returnValue; 
} 
static public string DecodeFrom64(string encodedData) { 
    byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData); 
    string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes); 
    return returnValue; 
} 
MessageBox.Show(DecodeFrom64("aHR0cDovL3d3dy5pbWRiLmNvbS90aXRsZS90dDA0MDE3Mjk=")); 

使用System.Text.UTF8Encoding.UTF8.GetBytes(...)如果字符串toEncode包含ASCII之外的字符。請注意,在這種情況下,解碼URL的任何一方都必須能夠正確處理這些字符。

而且看看大衛哈丁提到=+/the case,看看是否有任何提及的問題適用於您。或者只是使用David的answer

jQuery的:谷歌的jQuery使用Base64編碼'(網站plugins.jquery.com似乎在此刻脫機,所以我不能檢查它肯定)

2

Javascript成爲

var encodedStr = window.btoa("StringToEncode"); 

var decodedStr = window.atob(encodedStr); //"StringToEncode" 
0

我不要認爲尤金Ryabtsev接受的答案是正確的。 如果你用「\ XFF」試試吧,你會發現:

DecodeFrom64(EncodeTo64("\xff")) == "?" (i.e. "\x3f") 

的原因是,ASCIIEncoding不從128到255將不被理解走得更遠不是代碼127的所有字符並將被轉換爲「?」。

所以,擴展編碼是必要的,如下:

static public string EncodeTo64(string toEncode) { 
    var e = Encoding.GetEncoding("iso-8859-1"); 
    byte[] toEncodeAsBytes = e.GetBytes(toEncode); 
    string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); 
    return returnValue; 
} 
static public string DecodeFrom64(string encodedData) { 
    var e = Encoding.GetEncoding("iso-8859-1"); 
    byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData); 
    string returnValue = e.GetString(encodedDataAsBytes); 
    return returnValue; 
} 
+0

網上只有兩種編碼:ASCII和UTF-8。根據意圖,使用其他任何東西都是瘋狂或應用考古學。使用UTF-8並獲得upvote。 –

3

這是更好地使用下面的代碼從https://stackoverflow.com/a/1789179

///<summary> 
/// Base 64 Encoding with URL and Filename Safe Alphabet using UTF-8 character set. 
///</summary> 
///<param name="str">The origianl string</param> 
///<returns>The Base64 encoded string</returns> 
public static string Base64ForUrlEncode(string str) 
{ 
    byte[] encbuff = Encoding.UTF8.GetBytes(str); 
    return HttpServerUtility.UrlTokenEncode(encbuff); 
} 
///<summary> 
/// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8. 
///</summary> 
///<param name="str">Base64 code</param> 
///<returns>The decoded string.</returns> 
public static string Base64ForUrlDecode(string str) 
{ 
    byte[] decbuff = HttpServerUtility.UrlTokenDecode(str); 
    return Encoding.UTF8.GetString(decbuff); 
} 

原因是Base64編碼包含無效的URL字符。

+0

看來這些是有效的URL字符。儘管如此,使用它們仍然與常見的解碼/解釋方案混淆。 +1 –

相關問題