TyForHelpDude
TyForHelpDude

Reputation: 5002

Valid Base64 string can't be decoded

I have a valid base64 string that I can decode it in online tools but when it comes to line below;

string token = "eyJ1bmlxdWVfbmFtZSI6InllbmVyLnlpbG1hekB5ZHlhemlsaW0uY29tIiwiZ2l2ZW5fbmFtZSI6Ik1laG1ldCBZZW5lciIsImZhbWlseV9uYW1lIjoiWUlMTUFaIiwiZW1haWwiOiJ5ZW5lci55aWxtYXpAeWR5YXppbGltLmNvbSIsInJvbGUiOiJBZG1pbiIsIm5iZiI6MTU4NTI0OTI1NCwiZXhwIjoxNTg1ODU0MDU0LCJpYXQiOjE1ODUyNDkyNTR9==";
try
{
    var asd = Convert.FromBase64String(token);
}
catch (Exception ex)
{
    throw;
}

It throws exception..

Exception Message:

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

Why does this happen?

Upvotes: 0

Views: 2203

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

As Base64 string maps each byte 6 bits to 8 bits so each 3 bytes (24 bits) become 4 bytes. Base64 string length must be divisible to 4, if not as many = characters as needed are added to the end of it (which is actually not part of its content) to make the length divisible to 4.

As your Base64 string length is already divisble by 4, there is no need for extra = characters.

Upvotes: 2

Luca
Luca

Reputation: 352

You could have checked the validator.

This works:

    string s  = "eyJ1bmlxdWVfbmFtZSI6InllbmVyLnlpbG1hekB5ZHlhemlsaW0uY29tIiwiZ2l2ZW5fbmFtZSI6Ik1laG1ldCBZZW5lciIsImZhbWlseV9uYW1lIjoiWUlMTUFaIiwiZW1haWwiOiJ5ZW5lci55aWxtYXpAeWR5YXppbGltLmNvbSIsInJvbGUiOiJBZG1pbiIsIm5iZiI6MTU4NTI0OTI1NCwiZXhwIjoxNTg1ODU0MDU0LCJpYXQiOjE1ODUyNDkyNTR9";
    var c = Convert.FromBase64String(s);
    Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(c));

Upvotes: 1

Related Questions