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

4

9

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);
    }
}
Jigger answered 25/5, 2018 at 8:21 Comment(12)
Please post the string you are trying to decode (if it's not too huge).Heiduc
What exception is thrown and where is it thrown from?Crenulation
If it's huge, use PasteBin.Felishafelita
The error seems to suggest that your input is wrong. Have you checked, that your input string is correct?Botch
Maybe try looking at the raw base64 string (e.g. set a breakpoint and set a watch) and searching for non-base 64 characters, more than two padding characters, or an illegal character among the padded characters. I don't know, just a hunch.Anthea
Additionally, it's not really clear why you're not just using Encoding.UTF8.GetString(todecode_byte) after the base64 decoding. But that's aside from the base64 part not working, of course.Calliope
Maybe check the input and make sure you supplied only the base64 and not, for example, a json string containing a base64 value.Anthea
- isn't a valid character. Where is your string coming from? You might need to change - characters to either + or /. Also it must be a multiple of 4 characters long. Unless I've miscounted, your string has 43 characters.Heiduc
We are receiving this from our internal upstream interface where they claims the string is Base64 encoded url. Yes the length is 43? Are you sure that the key is not Base64 URL EncodedJigger
You can append = characters to make it the right length (i.e. a multiple of 4), but that still leaves the issue with the invalid - character. You'll need to know the encoding method that they used so you know how to fix it up for .Net.Heiduc
Thanks Matthew for your comments. The input string was not correct and caused this issue.Jigger
Im having this same issue except my string is coming from AESEncryptionLegato
H
31

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);
}
Heiduc answered 25/5, 2018 at 9:12 Comment(1)
This keeps giving me the same error: #75853810Chavannes
G
1

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);
}
Gleeson answered 9/7, 2021 at 5:49 Comment(0)
F
0

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 )

Frazee answered 15/6, 2023 at 8:2 Comment(0)
A
-2

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 "="

Akene answered 25/5, 2018 at 9:8 Comment(4)
This works. So It means the input string i was using is not correct one. Thank You.Jigger
You can't just remove the minus! You're changing the results. You need to replace it with the correct character.Heiduc
Right. This sample is working but changing the resultsJigger
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 inputAkene

© 2022 - 2024 — McMap. All rights reserved.