如何实现在C#中的Base64 URL安全编码? [英] How to achieve Base64 URL safe encoding in C#?
问题描述
我要实现在C#中的Base64 URL安全编码。在Java中,我们有共同的 codeC
库,它给了我一个网址安全连接codeD字符串。我怎样才能达到同样的使用C#?
I want to achieve Base64 URL safe encoding in C#. In Java, we have the common Codec
library which gives me an URL safe encoded string. How can I achieve the same using C#?
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes("StringToEncode");
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
以上code将其转换为Base64,但它垫 ==
。是否有办法实现网址安全编码?
The above code converts it to Base64, but it pads ==
. Is there is way to achieve URL safe encoding?
推荐答案
这是常见的只需简单更换字母的在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.
这篇关于如何实现在C#中的Base64 URL安全编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!