9

I'm beating my head against a wall here, with this simple code that just doesn't work:

string middle = "eyJzdWIiOiJtYXR0d2ViZXIiLCJqdGkiOiJlMWVmNjc5Mi02YTBjLTQ4YWUtYmQzNi0wZDlmMTVlMDFiY2UiLCJpYXQiOjE0OTMwOTI0OTQsIm5iZiI6MTQ5MzA5MjQ5NCwiZXhwIjoxNDkzMjY1Mjk0LCJpc3MiOiJFQ29tbVdlYkFQSTIiLCJhdWQiOiJFQ29tbVdlYkNsaWVudDIifQ"

byte[] newBytes = Convert.FromBase64String(middle);
middle = Encoding.UTF8.GetString(newBytes);

It's that simple! And yet I get the error in the Title.

Also, I ran this on https://www.base64decode.org/ and it decodes perfectly.

crackedcornjimmy
  • 1,972
  • 5
  • 26
  • 42

2 Answers2

16

Since your provided string does not completely fit criteria of FromBase64String method accepted values you need to add end symbol to follow the convention. It does not automatically add end symbols to your string.

The valueless character, "=", is used for trailing padding. The end of s can consist of zero, one, or two padding characters.

Source.

To fix issue you are having add "==" to the end of your string.

For example: string middle = "SomeString=="

Karolis Kajenas
  • 1,523
  • 1
  • 15
  • 23
  • 1
    There is a bit more to that in general case as sometimes there is a need to add single '=' instead of 2 of them and some times the input string already "good to go" without any padding. – Sevenate May 26 '21 at 01:58
2

To address the exception you are facing:

    public static string Base64UrlDecode(this string base64)
    {
        string padded = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');
        return Encoding.UTF8.GetString(Convert.FromBase64String(padded));
    }

All credits goes to the accepted answer here Code for decoding/encoding a modified base64 URL.

Sevenate
  • 6,221
  • 3
  • 49
  • 75