code解码/编码修改的base64 URL [英] Code for decoding/encoding a modified base64 URL

查看:373
本文介绍了code解码/编码修改的base64 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要为Base64 EN code数据把它放在一个URL,然后去code将其内我HttpHandler的。

I want to base64 encode data to put it in a URL and then decode it within my HttpHandler.

我发现, Base64编码允许一个/字符这会搞乱了我UriTemplate匹配。后来我发现,有一个修改的Base64 URL维基百科的一个概念:

I have found that Base64 Encoding allows 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:

A存在,在没有填充'='将被使用,和标准Base64的+和/字符分别被替换成' - '和'_',因此使用URL EN codeRS /解codeRS不再是必要的,对连接codeD值的长度没有影响,留下相同的EN codeD的形式保存完好,为关系数据库,Web表单的使用,和对象标识符一般。

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.

使用.NET我想从做基本base64编码和解码使用修改的Base64 URL的方法修改我目前的code。有没有人这样做呢?

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?

要取消code,我知道它开始出来的东西,如:

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('/', '_');

我见过的 GUID来的Base64网址 StackOverflow的条目,但有已知长度,因此,他们可以硬code的结尾需要等号的数量。

I have seen the Guid to Base64 for URL StackOverflow entry, but that has a known length and therefore they can hardcode the number of equal signs needed at the end.

推荐答案

这应该正确地垫出来: -

This ought to pad it out correctly:-

 base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');

这篇关于code解码/编码修改的base64 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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