【发布时间】:2017-11-01 21:26:45
【问题描述】:
我正在尝试从 Base64 字符串转换。首先我尝试了这个:
string a = "BTQmJiI6JzFkZ2ZhY";
byte[] b = Convert.FromBase64String(a);
string c = System.Text.Encoding.ASCII.GetString(b);
然后出现异常 - System.FormatException 被捕获 Message=Invalid length for a Base-64 char array。
所以在谷歌搜索之后,我尝试了这个:
string a1 = "BTQmJiI6JzFkZ2ZhY";
int mod4 = a1.Length % 4;
if (mod4 > 0)
{
a1 += new string('=', 4 - mod4);
}
byte[] b1 = Convert.FromBase64String(a1);
string c1 = System.Text.Encoding.ASCII.GetString(b1);
这里出现异常 - System.FormatException 被捕获 Message=Invalid character in a Base-64 string。
“BTQmJiI6JzFkZ2ZhY”中有无效字符吗?还是长度问题?
编辑:我首先使用以下代码解密输入字符串:
string sourstr, deststr,strchar;
int strlen;
decimal ascvalue, ConvValue;
deststr = "";
sourstr = "InputString";
strlen = sourstr.Length;
for (int intI = 0; intI <= strlen - 1; intI++)
{
strchar = sourstr.Substring(intI, 1);
ascvalue = (decimal)strchar[0];
ConvValue = (decimal)((int)ascvalue ^ 85);
if ((char)ConvValue.ToString().Length == 0)
{
deststr = deststr + strchar;
}
else
{
deststr = deststr + (char)ConvValue;
}
}
这个输出 deststr 被传递到下面的代码
Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(deststr));
这是我得到“BTQmJiI6JzFkZ2ZhY”的地方
【问题讨论】:
-
试试这个
System.Text.Encoding.UTF8.GetString(b) -
可能是填充问题? en.wikipedia.org/wiki/Base64#Base64_table 说虽然理论上解码不需要它,但一些实现仍然坚持它。
-
4&&":'1dgfa的 Base64 应该是NCYmIjonMWRnZmE=。解码你的在浏览器中给我[]4&&":'1dgfa([]作为不可显示的字节值字符的替换),如果我应用 URL 编码,它显示为"%054%26...,所以你有一个05字节值在您的4字符之前。这是否有意义,我想只有编码原始值的人才能告诉你。 -
我只是在问@kingfisher 从哪里得到那个字符串。
-
然后分享该代码。好像出了点问题。