Base-64 char数组异常的长度无效 [英] Invalid length for a Base-64 char array exception

查看:96
本文介绍了Base-64 char数组异常的长度无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在运行此代码时遇到异常

i have exception when i run this code ,, what is wrong

   var encoder = new System.Text.UTF8Encoding();
   System.Text.Decoder utf8Decode = encoder.GetDecoder();
   byte[] todecodeByte = Convert.FromBase64String(encodedMsg);
   int charCount = utf8Decode.GetCharCount(todecodeByte, 0, todecodeByte.Length);
   var decodedChar = new char[charCount];
   utf8Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decodedChar, 0);
   var message = new String(decodedChar);

此行出现例外

byte[] todecodeByte = Convert.FromBase64String(encodedMsg);


推荐答案

Base64编码每个字符编码6位。因此,字符串的长度乘以6,就必须被8整除。如果不是,则它没有足够的位来填充每个字节,您将得到此异常。

Base64 encoding encodes 6 bits per character. So the length of the string, multiplied by 6, must be divisible by 8. If it is not then it doesn't have enough bits to fill every byte and you'll get this exception.

很有可能 encodedMsg 并不是正确编码的base64字符串。您可以附加一些=字符来绕过该异常,并查看是否弹出任何可识别的内容。 =字符是base64的填充字符:

So good odds that encodedMsg just isn't a properly encoded base64 string. You can append some = characters to bypass the exception and see if anything recognizable pops out. The = character is the padding character for base64:

while ((encodedMsg.Length * 6) % 8 != 0) encodedMsg += "=";
// etc...

这篇关于Base-64 char数组异常的长度无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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