The Input Is Not a Valid Base-64 String as It Contains a Non-Base 64 Character

The input is not a valid Base-64 string when decoding valid base64 string

As suggested by Martin, replacing with UTF8 works.

So FromBase64Transform or CryptoStream may only support UTF8

Working code:

string expectedString = "this is a test";
byte[] expectedBytes = Encoding.Unicode.GetBytes(expectedString);
string base64String = Convert.ToBase64String(expectedBytes);
var input = new MemoryStream(Encoding.UTF8.GetBytes(base64String));
using FromBase64Transform myTransform = new FromBase64Transform();
using CryptoStream cryptoStream = new CryptoStream(input, myTransform, CryptoStreamMode.Read);

using var sr = new StreamReader(cryptoStream);
string str = await sr.ReadToEndAsync(); // OK

// Note: str != expectedString 'literally' because base64String is UTF-16 and we've used Encoding.UTF8 to get the bytes from it.

Thanks!

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

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);

}
}

ystem.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character

So the problem was just that the field in my database wasn't long enough. It was generating properly the hash.



Related Topics



Leave a reply



Submit