如何对URL进行BASE64编码?

3
5个回答

8

在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="));

如果字符串toEncode中包含ASCII之外的字符,使用System.Text.UTF8Encoding.UTF8.GetBytes(...)函数进行编码。请注意,在这种情况下,任何解码URL的一方都必须能够正确处理这些字符。
此外,请查看David Hardin提到的=+/案例,看看涉及的问题是否适用于您。或者直接使用David的答案
jQuery: 谷歌搜索'jquery base64 encode'(目前plugins.jquery.com网站似乎已经离线,所以无法确认)。

5

建议使用以下代码,来源于https://dev59.com/13M_5IYBdhLWcg3wymU0#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字符。

这些似乎是有效的URL字符。然而,使用它们会干扰常见的解码/解释方案。+1 - Eugene Ryabtsev

2

JavaScript-

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

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

0

0

我不认为 Eugene Ryabtsev 给出的被接受答案是正确的。 如果你用 "\xff" 来试一下,你会发现:

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

原因是ASCIIEncoding无法超过代码127。从128到255的所有字符都无法被理解,并将转换为“?”。

因此,需要使用扩展编码,如下所示:

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;
}

网络上只有两种编码:ASCII和UTF-8。使用其他任何编码都是疯狂的行为或应用考古学,这取决于意图。使用UTF-8并获得点赞。 - Eugene Ryabtsev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接