Why is this an issue?
When encrypting data with the Cipher Block Chaining (CBC) mode an Initialization Vector (IV) is used to randomize the encryption, ie under a given
key the same plaintext doesn’t always produce the same ciphertext. The IV doesn’t need to be secret but should be unpredictable to avoid
"Chosen-Plaintext Attack".
To generate Initialization Vectors, NIST recommends to use a secure random number generator.
Noncompliant code example
public void Encrypt(byte[] key, byte[] data, MemoryStream target)
{
byte[] initializationVector = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
using var aes = new AesCryptoServiceProvider();
var encryptor = aes.CreateEncryptor(key, initializationVector); // Noncompliant, hardcoded value is used
using var cryptoStream = new CryptoStream(target, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(data);
}
Compliant solution
public byte[] Encrypt(byte[] key, byte[] data, MemoryStream target)
{
using var aes = new AesCryptoServiceProvider();
var encryptor = aes.CreateEncryptor(key, aes.IV); // aes.IV is automatically generated to random secure value
using var cryptoStream = new CryptoStream(target, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(data);
return aes.IV;
}
Resources