Secure encryption modes and padding

Use encryption modes and padding appropriate to each algorithm.

Description

With AES-ECB, identical plaintext blocks produce identical ciphertext blocks. For RSA encryption, distinguishable padding errors during decryption can expose data protected with PKCS#1 v1.5.

Potential impact

Ciphertext patterns can reveal the structure of a message. An application that skips integrity checks may accept altered data.

Remediation

For AES, use GCM or CCM and never reuse a nonce with the same key. Send the nonce and tag with the ciphertext and accept plaintext only after verifying the tag. For RSA encryption, use OAEP. If you need to authenticate the sender, verify a signature or use separate authentication.

Examples

Supply suitable keys for each algorithm. The excerpts construct cipher objects.

AES ECB / GCM

Before

python
# AES encryption using ECB mode
from Crypto.Cipher import AES

cipher = AES.new(key, AES.MODE_ECB)

After

python
# AES-GCM cipher construction
from Crypto.Cipher import AES

AES.new(key, AES.MODE_GCM) # Use GCM mode.

Explanation

AES.new(key, AES.MODE_GCM) constructs a GCM object. When encrypting, retain its nonce and the resulting authentication tag.

RSA RSAES-PKCS1-v1_5 / OAEP

Before

python
# RSA encryption using RSAES-PKCS1-v1_5
from Crypto.Cipher import PKCS1_v1_5

PKCS1_v1_5.new(key)

After

python
# RSA encryption using OAEP
from Crypto.Cipher import PKCS1_OAEP

PKCS1_OAEP.new(key)

The legacy RSAES-PKCS1-v1_5 decryption path can expose a padding oracle through distinguishable errors. For OAEP, the PKCS1_OAEP.new(key) call defaults to SHA-1. In new configurations, select a hash such as SHA-256 explicitly at both ends.

References