C# Aes encrypt MemoryStream.ToArray为空
我的C# Aes encrypt MemoryStream.ToArray为空,c#,encryption,aes,C#,Encryption,Aes,我的AesEncrypt有问题,我有一段加密文本的代码: private byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV) { // Check arguments. if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException("plainText");
AesEncrypt
有问题,我有一段加密文本的代码:
private byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Padding = PaddingMode.None;
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
csEncrypt.FlushFinalBlock();
}
}
encrypted = msEncrypt.ToArray();
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
private byte[]EncryptStringToBytes_Aes(字符串明文,字节[]键,字节[]IV)
{
//检查参数。
如果(明文==null | |明文.Length您需要在调用FlushFinalBlock()
之前刷新swEncrypt
,以确保您尝试加密的所有数据都传递到加密流
改变
swEncrypt.Write(plainText);
csEncrypt.FlushFinalBlock();
到
进行此更改后,CryptoStream
现在将抛出一个异常,如果输入不是块大小的倍数,在AES的情况下为16字节
您有两个选项来解决此问题
手动将输入填充到块大小的倍数。对于“这是一个测试字符串”
,您可以将其填充到类似于“这是一个测试字符串\0\0\0\0\0\0\0\0”
。填充字符可以是您想要的任何字符,只要确保在解密后删除填充即可
将填充模式更改为其他模式,如PKCS7
或Zeros
。除非您绝对需要使用PaddingMode。无
(例如,为了与其他系统兼容),这是更好的解决方案
我创建了一个示例项目…为什么不简单地encrypted=encryptor.TransformFinalBlock(明文,0,明文.Length)
?流对于增量加密很有用,但如果您将整个消息放在一个数组中,则没有理由跳过所有这些限制。我将paddingmode更改为PKCS7,现在对字符串进行加密,但无法解密。我使用示例更新项目。没有任何内容……同样使用Flush(),返回错误“填充无效且无法删除”更新答案。您遇到的“填充无效”问题是由以下Encoding.Unicode.GetString(加密)引起的
encrypted
包含二进制,尝试将其转换为unicode会损坏数据。如果要将encrypted
转换为字符串,则需要将其编码为十六进制或Base64。
swEncrypt.Write(plainText);
swEncrypt.Flush();
csEncrypt.FlushFinalBlock();