Hardcoded encryption IV

Hardcoded initialization vector in encryption

Description

When AES-CBC reuses a key and a fixed initialization vector (IV), identical first plaintext blocks produce identical ciphertext blocks.

Potential impact

Comparing ciphertexts can reveal shared message prefixes. CBC alone cannot detect tampering.

Remediation

Use a vetted library to generate a fresh, unpredictable 16-byte IV for each AES-CBC encryption. Use authenticated encryption to detect changes. If you retain CBC, authenticate the IV and ciphertext together with a separate key, and verify the tag before decryption. Other modes have their own IV requirements.

Examples

Both examples read the ENCRYTION_KEY environment variable. Its UTF-8 encoded value must be a 16-, 24- or 32-byte AES key.

Before

python
# AES-CBC with a hardcoded IV
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

key = os.environ["ENCRYTION_KEY"].encode()
cipher = AES.new(key, AES.MODE_CBC, b'This is an IV456') # Hardcoded IV
plaintext = b'This is a secret message.'
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))

After

python
# AES-CBC with a fresh random IV
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes

key = os.environ["ENCRYTION_KEY"].encode()
iv = get_random_bytes(16)  # Random IV
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = b'This is a secret message.'
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))

get_random_bytes(16) generates the IV passed to AES.new. Keep it with the ciphertext for decryption.

References