Search code examples
c#exceptiondecodeencode

Invalid length for a Base-64 char array exception


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

Solution

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