Search code examples
c#base64decode

The input is not a valid Base-64 string how to solve


I have the following code:

var test = "eyJhbGciOiJSUzI1NiIsImtpZCI6IlRlc3RDZXJ0IiwidHlwIjoiYXQrand0In0";
var base64EncodedBytes = System.Convert.FromBase64String(test);
var hidenString = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

and I get the following error: 'The 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.'

Any help? how do I decode this?

I went to this website https://www.base64decode.org/ and decode the string, so the string can be decoded. I would expect my code to work, the string produced by the website was {"alg":"RS256","kid":"TestCert","typ":"at+jwt"}


Solution

  • If you encode properly, your base64 should look like this:

    eyJhbGciOiJSUzI1NiIsImtpZCI6IlRlc3RDZXJ0IiwidHlwIjoiYXQrand0In0=
    

    Notice the padding with a = in the end. You need to fix your base64 string, wherever it came from. The FromBase64String method is correct in complaining.