Invalid length for a Base-64 char array exception

六眼飞鱼酱① 提交于 2019-12-23 04:34:21

问题


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);

exception occurs in this line

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

回答1:


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.

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...


来源:https://stackoverflow.com/questions/12962992/invalid-length-for-a-base-64-char-array-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!