Lou
Lou

Reputation: 467

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

The below code throws a FormatException, although the input string is a valid base64 string.

Why?

System.FormatException 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.

string expectedString = "this";
byte[] expectedBytes = Encoding.Unicode.GetBytes(expectedString);
string base64String = Convert.ToBase64String(expectedBytes);
var input = new MemoryStream(Encoding.Unicode.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(); // Throws 
    
Assert.Equal(expectedString, str);

Upvotes: 0

Views: 17912

Answers (1)

Lou
Lou

Reputation: 467

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!

Upvotes: 3

Related Questions