我有一个问题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;
}
Run Code Online (Sandbox Code Playgroud)
问题是,在某些情况下,msEncrypt.ToArray()返回一个空的byte[],而在某些情况下,它工作得很好......
请拯救我的一天!
您需要swEncrypt在调用之前进行刷新FlushFinalBlock(),以确保您尝试加密的所有数据都传递到CryptoStream.
改变
swEncrypt.Write(plainText);
csEncrypt.FlushFinalBlock();
Run Code Online (Sandbox Code Playgroud)
到
swEncrypt.Write(plainText);
swEncrypt.Flush();
csEncrypt.FlushFinalBlock();
Run Code Online (Sandbox Code Playgroud)
进行此更改后,CryptoStream如果输入不是块大小的倍数(在 AES 中为 16 字节),现在将引发异常。
您有两种选择来解决此问题。
"This is a test string",您可以将其填充为类似这样的内容"This is a test string\0\0\0\0\0\0\0\0\0\0\0"。填充字符可以是任何你想要的,只要确保解密后删除填充即可。PKCS7或Zeros。除非您绝对需要使用PaddingMode.None(例如与其他系统兼容),否则这是更好的解决方案。