0

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?

Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
TyForHelpDude
  • 4,032
  • 8
  • 41
  • 76
  • 3
    It's not valid Base64. You don't need the padding (`==`); it invalidates the string. Without it, the length is evenly divisible by 4. – madreflection Mar 26 '20 at 19:17
  • Does this answer your question? [How to check for a valid Base64 encoded string](https://stackoverflow.com/questions/6309379/how-to-check-for-a-valid-base64-encoded-string) – Heretic Monkey Mar 26 '20 at 19:28

2 Answers2

2

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.

Ashkan Mobayen Khiabani
  • 30,915
  • 26
  • 90
  • 147
1

You could have checked the validator.

This works:

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