0

I have problem decode this base64 string, it always return ' Invalid length for a Base-64 char array or string'. But I managed to decode online at 'https://www.base64decode.org/'

These are my codes:

string base64Encoded = "eyJ4NXQjUzI1NiI6IndVWUdZWXp5dTJPMzNtVjY1WHFBVzBiTFlMeU5TU2VKZFlGTldKNnpzY0kiLCJ4NXQiOiJ0V3lmNTA0aTM3TXZxN0t1eEVyQTY4VTE4c1kiLCJraWQiOiJTSUdOSU5HX0tFWSIsImFsZyI6IlJTMjU2In0";

string base64Decoded;

byte[] data = Convert.FromBase64String(base64Encoded);

base64Decoded = Encoding.UTF8.GetString(data);
5
  • 2
    The error message is straightforward: your base64Encoded string value is not valid. It's missing the trailing '=' padding characters. You can add them back by appending the correct number of = characters. Commented Jul 23, 2018 at 3:19
  • There are 171 chars there @Dai, which is divisible by 3 (57 x 3). So no padding should be required. Commented Jul 23, 2018 at 3:27
  • 1
    @seesharper if you reencode the decoded string it gives you the padding. Commented Jul 23, 2018 at 3:31
  • Ah I see why @Droppy - the actual representation is not 1 character per byte. +1 Commented Jul 23, 2018 at 3:40
  • It might be worth checking that your base64 isn't one of the variants, some of which have different characters than the / and + that Convert.FromBase64String. Some variants don't require the = padding characters at the end, which is what makes me think that this could be a variant. Commented Jul 23, 2018 at 4:27

1 Answer 1

3

I've made some tests, and according to the comments you should not need the padding, but if you try to encode the decoded string: {"x5t#S256":"wUYGYYzyu2O33mV65XqAW0bLYLyNSSeJdYFNWJ6zscI","x5t":"tWyf504i37Mvq7KuxErA68U18sY","kid":"SIGNING_KEY","alg":"RS256"}

it gives you: eyJ4NXQjUzI1NiI6IndVWUdZWXp5dTJPMzNtVjY1WHFBVzBiTFlMeU5TU2VKZFlGTldKNnpzY0kiLCJ4NXQiOiJ0V3lmNTA0aTM3TXZxN0t1eEVyQTY4VTE4c1kiLCJraWQiOiJTSUdOSU5HX0tFWSIsImFsZyI6IlJTMjU2In0=

Notice the padding at the end.

Sign up to request clarification or add additional context in comments.

1 Comment

so.. the trick is to add the padding before decode, right? thanks @Droppy

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.