akshay
akshay

Reputation: 93

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

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

Upvotes: 9

Views: 37327

Answers (5)

I found a good answer to this problem.

Checkout here: Base64 decoding bug that is present in all version of .NET

In this site he explains a bug on .NET that I was having here with this Base64String: "JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL1hPYmplY3QvU3VidHlwZS9JbWFnZS9XaWR0aCA1Nzgv+PgolaVRleHQtNS41LjExCnN0YXJ0eHJlZgoyNzAxOQolJUVPRgo="

Basicaly you end with this code to solve and solved my life:

// This only works for base64 without spaces or linebreaks.
string Repad(string base64)
{
    var l = base64.Length;
    return l % 4 == 1 && base64[l - 1] == '='
        ? base64.Substring(0, l - 1)
        : base64;
}

Upvotes: 0

Ingmar
Ingmar

Reputation: 2658

Maybe it is a Base64Url encoded string (e.g.used for web tokens). Compared to Base64, those are not padded and use the characters - and _ instead of + and /.

(See RFC4648: https://datatracker.ietf.org/doc/html/rfc4648#section-5 .)

Either do the conversion on your own as demonstrated in other answers, or if you happen to work - by chance - at an ASP.NET project anyway, use

using Microsoft.IdentityModel.Tokens;

String decoded_string = Base64UrlEncoder.Decode( encoded_string );

(see: https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.base64urlencoder )

Upvotes: 0

Asad
Asad

Reputation: 508

I faced same issue while sending the password reset token in ASP.Net MVC application while using .Net 5 Identity Framework. Reset password token in URL was a valid URL Encoded Base64 String string but on binding of query parameter .Net Framework was creating problem by converting + sign into empty spaces. So after replacing empty spaces with + sign it's worked perfectly.

I have updated the DecodeUrlBase64 method from accepted answer of @Mathew Watson to handle empty spaces.

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

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109842

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

Upvotes: 33

kara
kara

Reputation: 3455

Your base64-String is not valid. It contains a - which is not allowed.

static void Main()
{
    string tmp = "eL78WIArGQ7bC44Ozr0yvUBkz9oc5YlsENYJilInSP==";
    byte[] tmp2 = Convert.FromBase64String(tmp);
}

-> Removed Minus -> Added two filler-chars "="

Upvotes: -2

Related Questions