Convert.FromBase64String() throws "invalid Base-64 string" error

23,890

So there are two issues:

  1. Your string is not a multiple of 4 long. It needs to be padded to a multiple of 4 using '=' characters.
  2. It looks like it's the format of base 64 used for URLs and suchlike, "modified Base64 for URL". This uses - instead of + and _ instead of /.

So to fix this, you need to swap - to + and _ to / and pad it, like so:

public static byte[] DecodeUrlBase64(string s)
{
    s = s.Replace('-', '+').Replace('_', '/').PadRight(4*((s.Length+3)/4), '=');
    return Convert.FromBase64String(s);
}
Share:
23,890
akshay
Author by

akshay

Updated on July 05, 2022

Comments

  • akshay
    akshay almost 2 years

    I have a key which is Base64 encoded.

    While trying to decode I am receiving the following error. The error is thrown by byte[] todecode_byte = Convert.FromBase64String(data);

    Error in base64DecodeThe input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

    I am using the below method to decode this:

    public string base64Decode(string data)
    {
        try
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
    
            byte[] todecode_byte = Convert.FromBase64String(data); // this line throws the exception
    
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
        catch (Exception e)
        {
            throw new Exception("Error in base64Decode" + e.Message);
        }
    }
    
  • akshay
    akshay almost 6 years
    This works. So It means the input string i was using is not correct one. Thank You.
  • Matthew Watson
    Matthew Watson almost 6 years
    You can't just remove the minus! You're changing the results. You need to replace it with the correct character.
  • akshay
    akshay almost 6 years
    Right. This sample is working but changing the results
  • kara
    kara almost 6 years
    I only wanted to show the problem. I'm sure everybody knows that interpretation of binary-data is not possible if you ignore some bytes ;). @akshay: Anyway - get some correct input