Symmetric Encryption (AES-GCM)
In symmetric encryption the same secret key encrypts and decrypts. It is fast enough to encrypt disks, databases and every byte of a TLS connection. The standard algorithm is AES (the Advanced Encryption Standard), with 128- or 256-bit keys. ChaCha20 is a popular alternative on devices without AES hardware.
Block ciphers need a mode
AES itself only transforms one 16-byte block. A mode of operation says how to encrypt longer messages. The choice matters a lot:
| Mode | Confidentiality | Detects tampering | Verdict |
|---|---|---|---|
| ECB | Leaks patterns: equal blocks give equal ciphertext | No | Never use |
| CBC | Yes, with a random IV | No (needs a separate MAC) | Legacy; easy to misuse |
| CTR | Yes, with a unique nonce | No | Building block |
| GCM | Yes, with a unique nonce | Yes (authentication tag) | Recommended |
| ChaCha20-Poly1305 | Yes, with a unique nonce | Yes | Recommended |
Modes that both encrypt and authenticate are called AEAD (authenticated encryption with associated data). Use AEAD: encryption without authentication lets an attacker modify ciphertext in ways that change the plaintext predictably, even without reading it.
Why ECB is dangerous
ECB encrypts each block independently, so identical plaintext blocks produce identical ciphertext blocks. Patterns survive encryption:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = bytes(range(16)) # DEMO ONLY
plaintext = b"ATTACK AT DAWN!!" * 3 + b"RETREAT AT DUSK!" # four 16-byte blocks
ecb = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
ct = ecb.update(plaintext) + ecb.finalize()
for i in range(0, len(ct), 16):
print(f"block {i // 16}: {ct[i:i + 16].hex()}")block 0: 8a21cef935d8587bea999da471a91c41
block 1: 8a21cef935d8587bea999da471a91c41
block 2: 8a21cef935d8587bea999da471a91c41
block 3: 937c126da0ada2674a0073d66207bb4f
Three identical ciphertext blocks reveal that the first three plaintext blocks are equal, without the key. On images, ECB famously leaves the outline of the picture visible.
Encrypting with AES-GCM
The cryptography package's AESGCM class does the right thing with minimal ceremony. You provide a key, a nonce (number used once, 12 bytes), the plaintext, and optional associated data: information that is authenticated but not encrypted, such as a record ID or header.
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
key = AESGCM.generate_key(bit_length=256) # new key every run: not printed
aes = AESGCM(key)
def encrypt(plaintext: bytes, record_id: bytes) -> bytes:
import os
nonce = os.urandom(12) # fresh nonce for every message
return nonce + aes.encrypt(nonce, plaintext, record_id)
def decrypt(blob: bytes, record_id: bytes) -> bytes:
nonce, ciphertext = blob[:12], blob[12:]
return aes.decrypt(nonce, ciphertext, record_id)
secret = b"IBAN DE89 3704 0044 0532 0130 00"
blob = encrypt(secret, b"customer:42")
print(len(secret), "byte message ->", len(blob), "byte blob (12 nonce + 16 tag)")
print(decrypt(blob, b"customer:42").decode())
print(encrypt(secret, b"customer:42") != blob) # new nonce, new ciphertext32 byte message -> 60 byte blob (12 nonce + 16 tag)
IBAN DE89 3704 0044 0532 0130 00
True
Storing the nonce in front of the ciphertext is the usual convention: the nonce isn't secret, it just must never repeat for the same key.
Tampering is detected
Change a single bit of the ciphertext, or use a different associated-data value, and decryption refuses with InvalidTag rather than returning altered data:
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag
key = bytes(32) # DEMO ONLY: fixed so the output is repeatable
nonce = bytes(12) # DEMO ONLY: never reuse in real code
aes = AESGCM(key)
ct = aes.encrypt(nonce, b"amount=100", b"order:7")
flipped = bytearray(ct)
flipped[7] ^= 0x01 # flip one bit
attempts = [
("original", bytes(ct), b"order:7"),
("bit flipped", bytes(flipped), b"order:7"),
("moved to other order", bytes(ct), b"order:8"),
]
for label, data, aad in attempts:
try:
print(f"{label:<22} {aes.decrypt(nonce, data, aad).decode()}")
except InvalidTag:
print(f"{label:<22} InvalidTag (rejected)")original amount=100
bit flipped InvalidTag (rejected)
moved to other order InvalidTag (rejected)
The third case shows why associated data is useful: binding a ciphertext to order:7 stops someone from copying an encrypted field from one record to another.
The nonce rule
With GCM (and CTR, and ChaCha20), reusing a nonce with the same key is catastrophic. Two messages encrypted with the same key and nonce are XORed with the same keystream, so XORing the two ciphertexts cancels the keystream and gives the XOR of the two plaintexts. GCM's authentication also breaks: the attacker can recover the authentication key and forge messages. Rules of thumb:
- Generate a random 96-bit nonce for every message, or use a counter that is never reset.
- With random nonces, rotate the key well before about 2³² messages.
- If you can't guarantee unique nonces, use a misuse-resistant mode such as AES-GCM-SIV.
Keys
Encryption moves the problem from protecting data to protecting keys:
- Generate keys with a secure random source, never from a password directly (use a KDF such as scrypt if you must start from a password).
- Store keys separately from the data they protect, ideally in a key management service (KMS) or hardware security module.
- Envelope encryption: encrypt data with a per-file data key, and encrypt the data key with a master key in the KMS. Rotating the master key then means re-encrypting small data keys, not all the data.
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
master = AESGCM(bytes(range(32))) # DEMO: in reality this key never leaves the KMS
data_key = bytes(range(100, 132)) # DEMO: really AESGCM.generate_key(256)
wrapped = master.encrypt(b"\x01" * 12, data_key, b"key-for:report.pdf")
file_ct = AESGCM(data_key).encrypt(b"\x02" * 12, b"Q3 revenue: 1.2M", None)
# later: unwrap the data key with the master key, then decrypt the file
unwrapped = master.decrypt(b"\x01" * 12, wrapped, b"key-for:report.pdf")
print(AESGCM(unwrapped).decrypt(b"\x02" * 12, file_ct, None).decode())
print("stored next to the file:", len(wrapped), "byte wrapped key")Q3 revenue: 1.2M
stored next to the file: 48 byte wrapped key
Go further: Block Cipher Modes: ECB, CBC and CTR encrypts a picture in each mode, and Nonce Reuse shows exactly what one repeated nonce breaks in GCM.
Test yourself
Why should ECB mode never be used?
- It is too slow
- Identical plaintext blocks give identical ciphertext blocks, leaking patterns
- It needs a 512-bit key
- It can't decrypt
What happens when you decrypt AES-GCM ciphertext that has been modified?
- You get slightly wrong plaintext
- Decryption fails with an authentication error (InvalidTag)
- The key is changed
- Nothing: GCM doesn't check
What is the most important rule about GCM nonces?
- They must be secret
- They must never repeat with the same key
- They must be 256 bits
- They must equal the key