C# 用于解码/编码修改后的 base64 URL 的代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1228701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Code for decoding/encoding a modified base64 URL
提问by Kirk Liemohn
I want to base64 encode data to put it in a URL and then decode it within my HttpHandler.
我想对数据进行 base64 编码以将其放入 URL,然后在我的 HttpHandler 中对其进行解码。
I have found that Base64 Encodingallows for a '/' character which will mess up my UriTemplate matching. Then I found that there is a concept of a "modified Base64 for URL" from wikipedia:
我发现Base64 编码允许使用 '/' 字符,这会弄乱我的 UriTemplate 匹配。然后我发现维基百科有一个“修改后的Base64 for URL”的概念:
A modified Base64 for URL variant exists, where no padding '=' will be used, and the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_', so that using URL encoders/decoders is no longer necessary and has no impact on the length of the encoded value, leaving the same encoded form intact for use in relational databases, web forms, and object identifiers in general.
存在针对 URL 变体的修改后的 Base64,其中不使用填充“=”,标准 Base64 的“+”和“/”字符分别替换为“-”和“_”,以便使用 URL 编码器/解码器不再需要并且对编码值的长度没有影响,保持相同的编码形式不变,以用于关系数据库、Web 表单和一般的对象标识符。
Using .NET I want to modify my current code from doing basic base64 encoding and decoding to using the "modified base64 for URL" method. Has anyone done this?
使用 .NET 我想修改我当前的代码,从执行基本的 base64 编码和解码到使用“修改的 base64 for URL”方法。有没有人做过这个?
To decode, I know it starts out with something like:
要解码,我知道它从以下内容开始:
string base64EncodedText = base64UrlEncodedText.Replace('-', '+').Replace('_', '/');
// Append '=' char(s) if necessary - how best to do this?
// My normal base64 decoding now uses encodedText
But, I need to potentially add one or two '=' chars to the end which looks a little more complex.
但是,我可能需要在末尾添加一两个 '=' 字符,这看起来有点复杂。
My encoding logic should be a little simpler:
我的编码逻辑应该简单一点:
// Perform normal base64 encoding
byte[] encodedBytes = Encoding.UTF8.GetBytes(unencodedText);
string base64EncodedText = Convert.ToBase64String(encodedBytes);
// Apply URL variant
string base64UrlEncodedText = base64EncodedText.Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
I have seen the Guid to Base64 for URLStackOverflow entry, but that has a known length and therefore they can hardcode the number of equal signs needed at the end.
我已经看到了URLStackOverflow 条目的Base64的Guid,但它有一个已知的长度,因此他们可以硬编码最后所需的等号的数量。
采纳答案by AnthonyWJones
This ought to pad it out correctly:-
这应该正确填充它:-
base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');
回答by Fredrik Haglund
Also check class HttpServerUtilitywith UrlTokenEncode and UrlTokenDecode methods that is handling URL safe Base64 encoding and decoding.
还要使用 UrlTokenEncode 和 UrlTokenDecode 方法检查类HttpServerUtility,这些方法处理 URL 安全 Base64 编码和解码。
Note 1: The result is not a valid Base64 string. Some unsafe characters for URL are replaced.
注 1:结果不是有效的 Base64 字符串。URL 的一些不安全字符被替换。
Note 2: The result differs from the base64url algorithm in RFC4648.
注 2:结果与 RFC4648 中的 base64url 算法不同。
///<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);
}
回答by Sushil
I hit here while looking for code to do encode/decode for base64url encoding which is little different than base64 as explained in the question.
我在寻找代码来对 base64url 编码进行编码/解码时点击这里,这与问题中解释的 base64 几乎没有什么不同。
Found c# code snippet in this document. JSON Web Signature ietf draft
在本文档中找到了 c# 代码片段。JSON Web 签名 ietf 草案
回答by Stefan Zvonar
Not enough points to comment, but in case it helps, the code snippet that Sushil found in the link provided (JSON Web Signature ietf draft) works for when encoding Base 64 as a parameter in URL.
没有足够的评论点,但如果有帮助,Sushil 在提供的链接(JSON Web 签名 ietf 草案)中找到的代码片段适用于将 Base 64 编码为 URL 中的参数。
Copied snippet below for those that are lazy:
为那些懒惰的人复制下面的片段:
static string Base64UrlEncode(byte[] arg)
{
string s = Convert.ToBase64String(arg); // Regular base64 encoder
s = s.Split('=')[0]; // Remove any trailing '='s
s = s.Replace('+', '-'); // 62nd char of encoding
s = s.Replace('/', '_'); // 63rd char of encoding
return s;
}
static byte[] Base64UrlDecode(string arg)
{
string s = arg;
s = s.Replace('-', '+'); // 62nd char of encoding
s = s.Replace('_', '/'); // 63rd char of encoding
switch (s.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: s += "=="; break; // Two pad chars
case 3: s += "="; break; // One pad char
default: throw new System.Exception(
"Illegal base64url string!");
}
return Convert.FromBase64String(s); // Standard base64 decoder
}
回答by Chris Halcrow
In comparison to the accepted answer, here is how you would fundamentally decodea base64 encoded url, using C#:
与接受的答案相比,以下是使用 C#从根本上解码base64 编码 url 的方法:
Decode:
解码:
string codedValue = "base64encodedUrlHere";
string decoded;
byte[] buffer = Convert.FromBase64String(codedValue);
decoded = Encoding.UTF8.GetString(buffer);