Base-64 char数组异常的长度无效

Tar*_*ied 0 c# encode decode exception

我运行此代码时有异常,出了什么问题

   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);
Run Code Online (Sandbox Code Playgroud)

此行发生异常

byte[] todecodeByte = Convert.FromBase64String(encodedMsg);
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

Base64编码每个字符编码6位.所以字符串的长度乘以6必须可以被8整除.如果不是那么它没有足够的位来填充每个字节,你就会得到这个异常.

如此好的几率,编码Msg不是一个正确编码的base64字符串.您可以附加一些=字符来绕过异常并查看是否有任何可识别的内容弹出.=字符是base64的填充字符:

while ((encodedMsg.Length * 6) % 8 != 0) encodedMsg += "=";
// etc...
Run Code Online (Sandbox Code Playgroud)