Part 1 · 2 chapters · ~12 min
Symmetric Ciphers and Modes
Block and stream ciphers, AES and ChaCha20, why ECB leaks and CBC needs care, CTR and GCM, AEAD with associated data, nonce rules and the cost of reuse, key sizes and rotation, envelope encryption, and field-level encryption for personal data.
3
AEAD in practice
code
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
function encryptField(key: Buffer, plaintext: string, customerId: string) {
const iv = randomBytes(12);
const c = createCipheriv('aes-256-gcm', key, iv); c.setAAD(Buffer.from(customerId));
const ct = Buffer.concat([c.update(plaintext, 'utf8'), c.final()]);
return Buffer.concat([iv, c.getAuthTag(), ct]).toString('base64'); // store iv ‖ tag ‖ ciphertext
}
function decryptField(key: Buffer, blob: string, customerId: string) {
const b = Buffer.from(blob, 'base64'), iv = b.subarray(0, 12), tag = b.subarray(12, 28), ct = b.subarray(28);
const d = createDecipheriv('aes-256-gcm', key, iv); d.setAAD(Buffer.from(customerId)); d.setAuthTag(tag);
return Buffer.concat([d.update(ct), d.final()]).toString('utf8'); // throws if tampered or wrong customer
}AUTHENTICATED ENCRYPTION (AEAD)
AES-256-GCM: confidentiality and integrity in one operation, 2,920 MB/s here
swipe the figure sideways, or tap expand for full screen
1/5
symmetric encryption
The same secret key encrypts and decrypts. AES (hardware-accelerated on modern CPUs) and ChaCha20 (fast in software, good on phones) are the current ciphers.
one key encrypts and decryptsAES or ChaCha20
4
Keys: size, rotation and envelopes
| question | answer |
|---|---|
| key size | AES-256 or ChaCha20 (256-bit keys); 128-bit AES is still secure, 256 adds margin |
| where keys live | a KMS or HSM, or Vault transit; never in code or the database next to the data |
| envelope encryption | data keys encrypt data; a master key in KMS encrypts the data keys (Config course part 3) |
| rotation | versioned keys: decrypt with any version, encrypt with the newest, re-wrap in the background |
| field-level encryption | encrypt BVNs, NINs and card data per field with AAD binding, so a database dump alone reveals nothing |