我对 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;
}
问题是,在某些情况下,msEncrypt.ToArray()
返回一个空的byte[]
,而在某些情况下,它工作得很好...
请拯救我的日子!
最佳答案
您需要在调用 FlushFinalBlock()
之前刷新 swEncrypt
,以确保您尝试加密的所有数据都传递到 CryptoStream
>.
改变
swEncrypt.Write(plainText);
csEncrypt.FlushFinalBlock();
至
swEncrypt.Write(plainText);
swEncrypt.Flush();
csEncrypt.FlushFinalBlock();
进行此更改后,如果输入不是 block 大小的倍数(在 AES 中为 16 字节),CryptoStream
现在将引发异常。
您有两种选择来解决此问题。
- 手动将输入填充到 block 大小的倍数。对于
“这是一个测试字符串”
,您可以将其填充为类似“这是一个测试字符串\0\0\0\0\0\0\0\0\0\0\0"
。填充字符可以是任何你想要的,只要确保解密后删除填充即可。 - 将填充模式更改为其他模式,例如
PKCS7
或Zeros
。除非您绝对需要使用PaddingMode.None
(例如为了与其他系统兼容),否则这是更好的解决方案。
关于c# - Aes 加密 MemoryStream.ToArray 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783182/