如何在 C# 中实现 Base64 URL 安全编码? [英] How to achieve Base64 URL safe encoding in C#?

查看:69
本文介绍了如何在 C# 中实现 Base64 URL 安全编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C# 中实现 Base64 URL 安全编码.在 Java 中,我们有通用的 Codec 库,它为我提供了一个 URL 安全编码字符串.如何使用 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);

上面的代码将其转换为Base64,但它填充了==.有没有办法实现URL安全编码?

The above code converts it to Base64, but it pads ==. Is there is way to achieve URL safe encoding?

推荐答案

简单地交换字母表用于 url 是很常见的,因此不需要 %-encoding;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);

然而,有趣的问题是:这是否与通用编解码器库"使用的方法相同?这肯定是一个合理的第一次测试 - 这是一种非常常见的方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆