Search code examples
c#base64characterconverters.net-6.0

Convert.FromBase64String gives the error of "The input is not a valid Base-64 string"


This is my string which i try to convert it from base64 to a humanly possible readable string:

eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9kYXRlb2ZiaXJ0aCI6IjIvMjUvMTk5MSAxMjowMDowMCBBTSIsIm5iZiI6MTY0MTQwNjk2MCwiZXhwIjoxNjQxNDEwNTYwLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo3MDAwLyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjcwMDAvIn0

It works on the online sites of converting from base64 like this site

On c# .net6 i try this code:

var bytes = Convert.FromBase64String(base64payload);

which base64payload is that above string. Why do i get this error on c# dotnet 6?

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

as far as i know,( a-z A-Z 0-9 / +) are valid and my eyes dont see any false base64 characters in this string + it works on elsewhere.


Solution

  • Your string is missing some padding. You can check for that here and repair it if you want to.

    The repaired and correct string is:

    eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9kYXRlb2ZiaXJ0aCI6IjIvMjUvMTk5MSAxMjowMDowMCBBTSIsIm5iZiI6MTY0MTQwNjk2MCwiZXhwIjoxNjQxNDEwNTYwLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo3MDAwLyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjcwMDAvIn0=
    

    After, use the following code:

    using System;
    using System.Text;
    
    namespace ConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                var coded = ("eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9kYXRlb2ZiaXJ0aCI6IjIvMjUvMTk5MSAxMjowMDowMCBBTSIsIm5iZiI6MTY0MTQwNjk2MCwiZXhwIjoxNjQxNDEwNTYwLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo3MDAwLyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjcwMDAvIn0=");
                string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(coded));
                Console.WriteLine(inputStr);
    
            }
        }