token要加编码decode吗_Base64编解码中的坑
本⽂主要针对 中的System.Web.ServerUtility.UrlTokenEncode()/UrlTokenDecode()进⾏解释
在巨硬的源码⽂档中到4.6.2的释义:
通过分析可知
1:最后⼀个‘=‘被编码成⼀个由源字符串与其长度差的加密字符.
2:‘+‘ to ‘-‘,‘/‘ to ‘_‘
相信看到这⾥读者都已经发现问题所在了,如果在不知道源字符串长度与最后⼀个补位符存在与否的情况下想解码获得源字符串是不⼤可能的。
那怎么办呢?⾃⼰⼿动写⼀个呗...
编码:
///
/// 字节码转为base64
/// 替换System.Web.ServerUtility.UrlTokenEncode⽅法
/// "/" to "_a","+" to "_b", and "=" to "_c"
///
///
///
internal static string UrlTokenEncode(byte[] input)
{
if (input == null)
throw new ArgumentNullException("input");
if (input.Length < 1)
return String.Empty;
string base64Str = null;
StringBuilder newbase64Str = new StringBuilder();
// Step 1: Do a Base64 encoding
base64Str = Convert.ToBase64String(input);
// Step 2: Copy in the other chars. Transform the "/" to "_a" ,"+" to "_b", and "=" to "_c"
foreach(var i in base64Str)
{
switch (i)
{
case ‘/‘:
newbase64Str.Append( "_a");
break;
case ‘+‘:
newbase64Str.Append( "_b");
break;
在线url网址编码解码case ‘=‘:
newbase64Str.Append( "_c");
break;
default:
newbase64Str.Append(i);
break;
}
}
return newbase64Str.ToString();
}
解码:
///
/// base64解码
///
///
///
internal static byte[] UrlTokenDecode(string input)
{
if (input == null)
throw new ArgumentNullException("input");
string newInput = input.Replace("_a", "/").Replace("_b", "+").Replace("_c", "="); int len = newInput.Length;
if (len < 1)
return new byte[0];
// Do the actual conversion
return Convert.FromBase64String(newInput);
}
不要问我为什么不把核⼼的编解码代码⾃⼰实现,因为懒。ok?

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。