I am using Rfc2898DeriveBytes
to generate an AES
key and iv
. However, I heard that the iv
should not be dependent on the password. Here's how I'm doing it right now:
byte[] salt = GenerateRandomBytes(32); // Generates 32 random bytes
using (Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(plainStrPassword, salt)) {
byte[] aesKey = rfc.GetBytes(32);
byte[] iv = rfc.GetBytes(16); // Should I do this or generate it randomly?
}
My question: Is it OK (secure) to generate the iv
from Rfc2898DeriveBytes
? Or should I generate it randomly using RNGCryptoServiceProvider
?
No, it's not secure to derive the IV from the same source from which you derive the key. The IV exists so that encryption of identical messages under the same key produces different ciphertexts.
You should use a cryptographically secure random source (such as RNGCryptoServiceProvider
you identified) to derive the IV and communicate it alongside the ciphertext (typically either prepended to the ciphertext as one stream of bytes or in a separate field within a more structured file format).