根据GregS对This Answer的评论,IV 应该添加到 AES 加密数据之前(假设我没看错):
把它放在密码之前。这样你就可以在流模式下解密。
在我看来,GregS 是在暗示有一种流模式,可以自动预先/解析加密中使用的 IV。
这是真的?
我目前正在手动将我的 IV 添加到加密数据中,并在解密之前手动将密码拆分为 IV 和数据。有没有一种方法可以自动执行此操作?
以供参考:
这就是我现在正在做的事情:
Encrypt
方法:
public byte[] Encrypt(byte[] data)
{
// Generate IV
var iv = new byte[BlockSize/8];
new Random().NextBytes(iv);
byte[] cipher = // encryption happens here
// Prepend IV to Cipher
var saltedCipher = new byte[iv.Length + cipher.Length];
Buffer.BlockCopy(iv, 0, saltedCipher, 0, iv.Length);
Buffer.BlockCopy(cipher, 0, saltedCipher, iv.Length, cipher.Length);
return saltedCipher;
}
Decrypt
方法:
public byte[] Decrypt(byte[] saltedCipher)
{
// Split saltedCipher into iv and cipher
var iv = new byte[BlockSize/8];
var cipher = new byte[saltedCipher.Length - iv.Length];
Buffer.BlockCopy(buffer, 0, iv, 0, iv.Length);
Buffer.BlockCopy(buffer, iv.Length, cipher, 0, cipher.Length);
byte[] data = // decryption happens here
return data;
}