0

このコードを実行すると例外が発生します。何が問題なのですか

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

1 に答える 1

6

Base64 エンコーディングは、1 文字あたり 6 ビットをエンコードします。そのため、文字列の長さを 6 倍すると、8 で割り切れる必要があります。そうでない場合は、すべてのバイトを埋めるのに十分なビットがなく、この例外が発生します。

encodingMsgが適切にエンコードされた base64 文字列ではない可能性が非常に高いです。いくつかの = 文字を追加して例外をバイパスし、認識可能なものが飛び出すかどうかを確認できます。= 文字は、base64 のパディング文字です。

while ((encodedMsg.Length * 6) % 8 != 0) encodedMsg += "=";
// etc...
于 2012-10-18T20:56:06.293 に答える