Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.FormatException: 'Invalid length for a Base-64 char array or string.'

Tags:

c#

base64

decode

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.

like image 364
crackedcornjimmy Avatar asked Apr 25 '17 05:04

crackedcornjimmy


1 Answers

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

like image 70
Karolis Kajenas Avatar answered Sep 25 '22 06:09

Karolis Kajenas