将字符串转换为加密 API 的字节数组
本文解释了为什么字符串编码不应该用于往返密文。但是,如果我尝试使用推荐的 Convert.ToBase64String
,如果原始字符串未使用 4 字节块打包,则会出现异常。在下面的示例中,原始字符串不起作用,但只有“Zoidberg”起作用,因为它有 8 个字节长(在使用 Convert.ToBase64String
时被打包到 6 字节数组中)。
正如本文中所承诺的,如果我使用任何字符串编码,则在解密回值时会收到“错误数据”错误。那么原始字符串应该如何作为字节数组输入到加密 API 中呢? <代码>
string text = "Zoidberg is important!";
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
// This throws FormatException: "The input is not a valid Base-64 string as it
// contains a non-base 64 character, more than two padding characters,
// or a non-white space character among the padding characters"
byte[] cipherText = provider.Encrypt(Convert.FromBase64String(text), false);
string plainText = Convert.ToBase64String(provider.Decrypt(cipherText, false));
This article explains why string Encoding shouldn't be used to round-trip the cipher text. However, if I try using recommended Convert.ToBase64String
, I get an exception if the original string is not packaged with 4-byte blocks. In the following example, the original string doesn't work, but just "Zoidberg" does, since it's 8 bytes long (that are packaged into a 6-byte array when Convert.ToBase64String
is used).
As promised in the article, if I use any string Encoding, I get "Bad Data" error when decrypting the value back. So how should the original string be fed into the crypto APIs as a byte array?
string text = "Zoidberg is important!"; RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); // This throws FormatException: "The input is not a valid Base-64 string as it // contains a non-base 64 character, more than two padding characters, // or a non-white space character among the padding characters" byte[] cipherText = provider.Encrypt(Convert.FromBase64String(text), false); string plainText = Convert.ToBase64String(provider.Decrypt(cipherText, false));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你被那篇文章误导了。
从
string -> 转换没有意义字节[] -->加密字节[] --> string
,这是该文章向您展示的不要做的内容。想必,您想要
string ->;字节[] ->加密字节[] -> (网络,无论什么)->加密字节[] ->字节[] -> string.
这样使用Encoding将字符串转换为字节就可以了。我不知道为什么您链接的文章会警告您不要获取加密字节并将其直接转换回字符串。看起来很傻。
你说你正在尝试往返密文,所以我会使用包含字符串加密字节的字节数组来实现这一点,而忘记 Base-64 编码。
I think you were mislead by that article.
It does not make sense to convert from
string -> byte[] --> encrypted byte[] --> string
, which is what that article is showing you to not do.Presumably, you want to go
string -> byte[] -> encrypted byte[] -> (network, whatever) -> encrypted byte[] -> byte[] -> string.
It's fine to use Encoding to convert the string to bytes in this manner.I don't know why the article you linked would warn you against taking the encrypted bytes and converting that directly back to a string. Seems silly.
You say you're trying to round-trip the ciphertext, so I would do so with byte arrays containing the encrypted bytes of your string and forget about base-64 encoding.