2012-05-27 82 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 –

相关问题