【问题标题】:Invalid length for a Base-64 char array exceptionBase-64 字符数组异常的长度无效
【发布时间】:2012-10-18 20:14:43
【问题描述】:

我运行这段代码时出现异常,有什么问题

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

【问题讨论】:

  • 需要更多信息。 encodedMsg的内容是什么?异常发生在哪里?等等……
  • 编码后的消息是否包含数字?

标签: c# exception decode encode


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-05-20
    • 2011-02-24
    • 1970-01-01
    相关资源
    最近更新 更多