[英]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.下面的代码抛出 FormatException,尽管输入字符串是有效的 base64 字符串。
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);
As suggested by Martin, replacing with UTF8 works.正如 Martin 所建议的那样,用 UTF8 替换是可行的。
So FromBase64Transform or CryptoStream may only support UTF8所以 FromBase64Transform 或 CryptoStream 可能只支持 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!谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.