且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实现在C#中的Base64 URL安全编码?

更新时间:2023-02-23 19:21:32

这是常见的只需简单更换字母的在URL中使用,所以没有%编码是必要的;只有65个字符的3是有问题的 - + / = 。最常见的替代品是 - + _ 的>在 / 的。至于填充:只是将其删除的(即 = );你可以的推断的需要填充量。在另一端:刚刚相反的过程:

It is common to simply swap alphabet for use in urls, so that no %-encoding is necessary; only 3 of the 65 characters are problematic - +, / and =. the most common replacements are - in place of + and _ in place of /. As for the padding: just remove it (the =); you can infer the amount of padding needed. At the other end: just reverse the process:

string returnValue = System.Convert.ToBase64String(toEncodeAsBytes)
        .TrimEnd(padding).Replace('+', '-').Replace('/', '_');

static readonly char[] padding = { '=' };

和扭转:

string incoming = returnValue
    .Replace('_', '/').Replace('-', '+');
switch(returnValue.Length % 4) {
    case 2: incoming += "=="; break;
    case 3: incoming += "="; break;
}
byte[] bytes = Convert.FromBase64String(incoming);
string originalText = Encoding.ASCII.GetString(bytes);

有趣的问题,但是,是:这是相同的做法,即共同codeC图书馆使用的这肯定会是测试一个合理的第一件事情 - 这是一个pretty常用的方法。

The interesting question, however, is: is this the same approach that the "common codec library" uses? It would certainly be a reasonable first thing to test - this is a pretty common approach.