解码有效的base64字符串时,输入不是有效的基本-64字符串
尽管输入字符串是有效的base64字符串,但下面代码会引发一个构造Xpection。
为什么?
system.formateXception输入不是有效的基本-64字符串,因为它包含一个非基本64个字符,超过两个填充字符或填充字符中的非法字符。
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如马丁所建议的那样,用UTF8作品代替。
因此,FromBase64Transform或CryptoStream只能支持UTF8
工作代码:
谢谢!
As suggested by Martin, replacing with UTF8 works.
So FromBase64Transform or CryptoStream may only support UTF8
Working code:
Thanks!