解码有效的 base64 字符串时,输入不是有效的 Base-64 字符串

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

尽管输入字符串是有效的 base64 字符串,但以下代码抛出 FormatException。

为什么?

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

按照 Martin 的建议,用 UTF8 替换就可以了。

因此 FromBase64Transform 或 CryptoStream 可能只支持 UTF8

工作代码:

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.

谢谢!