SecurityVol. 10 · Part X
0 / 0

Shelves / Security

SE·107

Cryptography Foundations

Applied cryptography for engineers: why you must never invent your own, secure randomness, hash functions and their properties, HMAC, password hashing with Argon2id, bcrypt, scrypt and PBKDF2, symmetric encryption with AES and authenticated modes (GCM, ChaCha20-Poly1305) and the danger of nonce reuse, asymmetric cryptography (RSA, elliptic curves, Ed25519), digital signatures, key exchange and forward secrecy, hybrid encryption, certificates, PKI and TLS 1.3 step by step, key management and rotation, and post-quantum cryptography, with correct code in Java, Go, Python, Rust and Node.

39 topics · ~32 min read · 31-question quiz
Updated Suggest a correction

Start here: cryptography you can watch work

Cryptography gives you a small set of tools, each answering one question. Pick the tool by the question, never by the name that sounds strongest.

Question Tool Example
Has this data changed? (no secret) hash SHA-256 of a download
Did someone holding our shared key send this? MAC HMAC-SHA256 on a webhook
Can anyone check that I sent this? signature Ed25519, ECDSA
Keep data secret and detect tampering authenticated encryption AES-256-GCM, ChaCha20-Poly1305
Agree a key over an open network key exchange X25519 (ECDH)
Store a password slow password hash Argon2id, bcrypt

Passwords: slow on purpose

A password table gets stolen eventually, so you store a hash an attacker must guess against. How fast each guess runs decides how long the passwords survive:

Text
bcrypt cost  8:    17.8 ms per hash  → ~56 guesses/s per core
bcrypt cost 10:    71.5 ms           → ~14 guesses/s
bcrypt cost 12:   277.9 ms           → ~4 guesses/s
bcrypt cost 14:  1118.8 ms           → ~1 guess/s
argon2id (t=3, 64 MiB): 149.3 ms     → ~7 guesses/s, and 64 MiB of RAM per guess
md5 in a tight loop:   448 ns/hash   → ~2.2 million guesses/s on ONE core (GPUs: billions)

Each step of bcrypt's cost doubles the work (cost 10→12 is 4×). MD5 is about 600,000 times faster than bcrypt cost 12 here, so a table of MD5'd passwords falls in hours. Argon2id adds a memory cost, which makes GPU and custom-hardware attacks far less efficient. Each hash also contains a random salt, so the same password hashed twice looks different and one precomputed table can't crack every user:

Text
$2b$10$CErb4elSQI8BZ8QjturvNOtTRDQd61GFn8M6U…
$2b$10$30NT1COcVXECjLD/IyhwQuTp8UKa6r9r3Z61v…

Authenticated encryption: secret and tamper-evident

AES-256-GCM encrypts and adds a 16-byte tag computed over the ciphertext and any associated data (here the account number, sent in the clear but bound to the message):

Text
ciphertext 37 bytes (21 plaintext + 16-byte tag)
decrypt untampered: transfer 100 to alice
tampered ciphertext (one bit flipped) rejected: InvalidTag
wrong associated data (account:99) rejected: InvalidTag

Encryption without authentication lets an attacker flip bits in the message undetected, so in new code you always use an authenticated (AEAD) mode.

The one rule GCM makes you keep: never reuse a nonce

Each GCM encryption needs a unique 12-byte nonce under the same key. Here two messages were encrypted with the same nonce on purpose:

Text
XOR of the two ciphertexts : 0000000009080909000000000c0d050f0a
XOR of the two plaintexts  : 0000000009080909000000000c0d050f0a
knowing p1, attacker recovers p2: PAY 9999 TO MALLO

The keystream cancels out, so the ciphertexts leak the XOR of the plaintexts; knowing (or guessing) one message reveals the other, and reuse also lets an attacker forge tags. Use random 96-bit nonces from a secure generator (and rotate the key well before about 2³² messages), or a counter you can prove never repeats.

Randomness: secure versus predictable

Text
secrets.token_urlsafe(16):            -DJREMQ6fIE6L0CPDADtXg
random with seed 42:                  [654, 114, 25]
random with seed 42 again:            [654, 114, 25]

random is a fast, predictable generator meant for simulations; anyone who learns its state can predict every value. Tokens, keys, nonces and reset links must come from the OS's cryptographic generator (secrets, SecureRandom, crypto.randomBytes, getrandom).

Public-key crypto, and why we still use symmetric keys

Text
X25519: both sides computed the same 32-byte secret: True (public keys: 32 bytes)
Ed25519 signature: 64 bytes      ECDSA P-256 signature: 71 bytes (DER)
ECDSA P-256 sign: 0.05 ms   RSA-2048 sign: 0.38 ms   RSA-3072: 1.03 ms   RSA-4096: 2.38 ms
RSA-4096 keygen: 670 ms     EC P-256 keygen: 0.1 ms
AES-256-GCM, 1 KiB: 1.8 µs (~566 MB/s on one core, in Python)

Two parties who have never met can each publish a 32-byte public key and compute the same secret (X25519); a KDF such as HKDF turns it into an AES key. Elliptic-curve keys are far smaller and faster than RSA at similar strength. Bulk data always goes through fast symmetric encryption; public-key operations only set up the key. That combination is hybrid encryption, and it is what TLS does.

TLS: all of it at once

An OpenSSL 1.3 server with a certificate signed by a lab CA:

Text
no CA trusted        → TLSv1.3, TLS_AES_256_GCM_SHA384, Verify return code: 21 (unable to verify)
trusting the lab CA  → Server Temp Key: X25519; Peer signature: ECDSA; Verify return code: 0 (ok)
wrong hostname       → Verify return code: 62 (hostname mismatch)
client offers 1.2    → alert protocol version (server is TLS 1.3 only)

The handshake used every tool above: X25519 key exchange (with fresh keys each connection, which gives forward secrecy), an ECDSA signature proving the server holds the certificate's key, a certificate chain the client must verify against a trusted CA and the expected hostname, then AES-256-GCM for the data. Notice that the connection was still encrypted when verification failed: encryption to an unverified party protects you from nobody, which is why disabling certificate verification is one of the most dangerous lines you can write.

How deep to go in cryptography foundations

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Name the tool for each job: hash, MAC, signature, AEAD, key exchange, password hash
L2 Use vetted libraries correctly: Argon2id/bcrypt, AES-GCM with unique nonces, CSPRNG tokens, verified TLS
L3 Explain why each construction is secure, what its assumptions are (nonce uniqueness, key separation) and how TLS 1.3 combines them
L4 Spot misuse in code review and incidents: nonce reuse, unauthenticated modes, disabled verification, weak KDFs, bad randomness
L5 Design key management, rotation, crypto-agility and a post-quantum migration for a system
L6 Set organisational cryptography standards, approved-algorithm lists and migration programmes

The first rule

Never invent cryptography. Don't design algorithms, protocols or "clever" encodings, and don't assemble primitives yourself if a vetted high-level construction exists.

Cryptography fails silently: broken code still produces random-looking output. Subtle mistakes (reusing a nonce, comparing MACs with ==, using ECB mode, encrypting without authenticating, rolling your own key derivation) turn strong algorithms into broken systems. Use:

  • High-level, misuse-resistant libraries: libsodium (and bindings: sodiumoxide/libsodium-sys, PyNaCl, sodium-native), Google Tink (Java, Go, Python, C++), age for file encryption, platform KMS services.
  • Standard protocols: TLS 1.3, OAuth/OIDC, JOSE/JWT done carefully, Signal protocol, Noise, HPKE.
  • Well-maintained language standard libraries for primitives when you must: Go's crypto/*, Java's JCA with modern providers, Python's cryptography package, Rust's RustCrypto crates and ring/aws-lc-rs, Node's crypto (OpenSSL), BoringSSL/AWS-LC/OpenSSL 3 in C/C++.

This chapter teaches what the primitives do so you can choose and use them correctly.

Randomness

Cryptography depends on unpredictable random numbers: keys, nonces, salts, session tokens, password reset links, CSRF tokens.

  • Use a cryptographically secure pseudo-random number generator (CSPRNG) seeded by the OS (getrandom(2) on Linux, BCryptGenRandom on Windows).
  • Never use general-purpose PRNGs (java.util.Random, math/rand, Python random, Math.random(), C rand()) for anything security-related: their output is predictable from a few observations.
Language Secure API
Java SecureRandom (SecureRandom.getInstanceStrong() only where blocking is acceptable)
Go crypto/rand (rand.Read, rand.Text() since Go 1.24)
Python secrets module (secrets.token_urlsafe(32)), os.urandom
Rust rand::rngs::OsRng, getrandom crate
Node.js crypto.randomBytes, crypto.randomUUID, Web Crypto getRandomValues
C getrandom(2), arc4random_buf (BSD/macOS/glibc 2.36+), libsodium randombytes_buf

Tokens should carry at least 128 bits of entropy (16 random bytes), typically encoded as base64url or hex.

Hash functions

Properties

A cryptographic hash function maps arbitrary input to a fixed-size digest with these properties:

Property Meaning
Pre-image resistance Given a digest h, infeasible to find any m with H(m) = h
Second pre-image resistance Given m₁, infeasible to find m₂ ≠ m₁ with the same hash
Collision resistance Infeasible to find any two distinct inputs with the same hash (birthday bound: ~2^(n/2) work for an n-bit hash)
Avalanche Changing one input bit changes about half the output bits

Which hash

Function Status
MD5, SHA-1 Broken for collisions (MD5 practically since 2004; SHA-1 since SHAttered, 2017). Never use for security (fine only as non-security checksums)
SHA-256 / SHA-384 / SHA-512 (SHA-2) Standard and safe. Vulnerable to length extension (given H(secret‖m), an attacker can compute H(secret‖m‖padding‖extra)), so never build MACs as SHA256(secret + message)
SHA-3 / SHAKE Different design (sponge), no length extension; safe alternative
BLAKE2 / BLAKE3 Very fast, secure; BLAKE3 is parallelisable and has keyed and KDF modes

Uses: integrity checksums of downloads (with a trusted digest), content addressing (Git, container images), digital signature inputs, Merkle trees, commitment schemes.

HMAC

A message authentication code (MAC) proves a message came from someone holding a shared secret key and wasn't modified. HMAC (RFC 2104) builds a MAC from a hash function securely, immune to length extension:

HMAC(K, m) = H((K ⊕ opad) ‖ H((K ⊕ ipad) ‖ m))

Uses: webhook signatures (GitHub, Stripe sign payloads with HMAC-SHA256), API request signing (AWS SigV4 uses chained HMACs), signed cookies, JWTs with HS256, key derivation (HKDF).

Verify in constant time: comparing MACs with == leaks, through timing, how many leading bytes matched, letting attackers forge MACs byte by byte. Use MessageDigest.isEqual (Java), hmac.Equal (Go), hmac.compare_digest (Python), crypto.timingSafeEqual (Node), the subtle/constant_time_eq crates or the MAC type's verify (Rust).

// Java: verify a webhook HMAC-SHA256 signature in constant time
static boolean verify(byte[] secret, byte[] body, String sigHex) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret, "HmacSHA256"));
    byte[] expected = mac.doFinal(body);
    byte[] provided = HexFormat.of().parseHex(sigHex);
    return MessageDigest.isEqual(expected, provided);        // constant-time comparison
}

Webhook verification should also check a timestamp (reject old messages, prevent replay) included in the signed content (chapter 110).

Password hashing

Why ordinary hashes are wrong for passwords

Passwords have low entropy. If you store SHA256(password), an attacker who steals the database can try billions of guesses per second on GPUs, and identical passwords produce identical hashes (rainbow tables). Password storage needs:

  1. A unique random salt per password (defeats precomputation and reveals nothing about reuse).
  2. A deliberately slow, memory-hard function (makes each guess expensive, especially on GPUs/ASICs).
  3. Tunable cost parameters that you raise as hardware improves.

Algorithms

Algorithm Notes OWASP-style parameters (2025–26 guidance)
Argon2id Winner of the Password Hashing Competition (2015); memory-hard; resists GPU and side-channel attacks. First choice e.g. m = 19 MiB, t = 2, p = 1 (or m = 46 MiB, t = 1); tune to ~100–500 ms on your servers
scrypt Memory-hard; good alternative N = 2^17, r = 8, p = 1
bcrypt Older, widely available, not memory-hard; truncates input at 72 bytes cost ≥ 10 (12 is common)
PBKDF2-HMAC-SHA256 Only when FIPS compliance requires it ≥ 600,000 iterations

The output string encodes algorithm, parameters and salt ($argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>), so you can upgrade parameters transparently: on successful login, if the stored hash uses old parameters, rehash the password with new ones.

Additional measures: a pepper (secret key held outside the database, e.g. in a KMS/HSM, applied via HMAC), rate limiting and lockout/backoff on login, breached-password checks (k-anonymity API of Have I Been Pwned), and MFA. Better still, reduce password use: passkeys (WebAuthn/FIDO2) are phishing-resistant and leave nothing crackable on your servers.

NIST SP 800-63B-4 (final, July 2025) reflects modern guidance: require length (at least 8 characters with MFA, 15 for password-only authentication), allow long passphrases and all characters, don't impose composition rules or periodic forced changes, do check against breached and common passwords, and force changes only on evidence of compromise.

// Java: Spring Security's Argon2 encoder (Bouncy Castle) with upgrade support
PasswordEncoder encoder = Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
String stored = encoder.encode(rawPassword);                 // includes salt and parameters
boolean ok = encoder.matches(attempt, stored);
// DelegatingPasswordEncoder ("{argon2}…", "{bcrypt}…") lets you migrate algorithms over time

Symmetric encryption

AES and authenticated encryption

Symmetric encryption uses the same key to encrypt and decrypt. It's fast and used for bulk data.

  • AES (Advanced Encryption Standard, Rijndael, 2001) is a block cipher on 128-bit blocks with 128-, 192- or 256-bit keys, hardware-accelerated (AES-NI, ARMv8 crypto extensions). ChaCha20 is a fast stream cipher, especially on devices without AES hardware.
  • A block cipher needs a mode of operation to encrypt more than one block:
Mode Verdict
ECB Never: identical plaintext blocks give identical ciphertext blocks (the famous "ECB penguin")
CBC Legacy; needs a random IV and a separate MAC (encrypt-then-MAC); padding-oracle attacks when done wrong
CTR Stream mode; no integrity on its own
GCM (AES-GCM) AEAD: confidentiality + integrity in one; standard choice
ChaCha20-Poly1305 AEAD: equally good; constant-time in software
AES-GCM-SIV, XChaCha20-Poly1305 AEAD variants tolerant of nonce reuse (GCM-SIV) or with 192-bit random nonces (XChaCha)

Always use authenticated encryption (AEAD). Encryption alone doesn't prevent tampering: an attacker can flip bits in CTR or CBC ciphertext to change the plaintext predictably. AEAD verifies a tag on decryption and fails if anything changed. It can also authenticate associated data (AD) that isn't encrypted but must not be altered (a record ID, a header, the tenant ID), binding the ciphertext to its context.

Nonces

AEAD modes need a nonce (number used once), typically 96 bits for AES-GCM. Reusing a nonce with the same key is catastrophic for GCM: it reveals the XOR of plaintexts and allows an attacker to forge messages (the authentication key can be recovered). Rules:

  • Use a random 96-bit nonce per message, and rotate keys well before 2^32 messages per key (random-nonce collision risk); or use counters carefully (never reset, never shared across instances); or use XChaCha20-Poly1305 (192-bit random nonces) or AES-GCM-SIV for misuse resistance.
  • Store the nonce alongside the ciphertext (it isn't secret).
// Java: AES-256-GCM with random nonce and associated data
static SecretKey newKey() throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(256);
    return kg.generateKey();
}

static byte[] encrypt(SecretKey key, byte[] plaintext, byte[] aad) throws Exception {
    byte[] nonce = new byte[12];
    new SecureRandom().nextBytes(nonce);
    Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce));
    c.updateAAD(aad);
    byte[] ct = c.doFinal(plaintext);                                   // ciphertext || 16-byte tag
    return ByteBuffer.allocate(12 + ct.length).put(nonce).put(ct).array();
}
// Decrypt: split nonce, init DECRYPT_MODE with same AAD; doFinal throws AEADBadTagException if tampered

(In real systems, prefer envelope encryption with a KMS (Vol. 7 ch. 88) or Tink's keysets, which handle key IDs, rotation and nonce management for you.)

Asymmetric cryptography

Key pairs

Asymmetric (public-key) cryptography uses a key pair: a private key kept secret and a public key shared freely. Operations:

  • Encryption: anyone encrypts with the public key; only the private key holder decrypts. (In practice used to transport symmetric keys: hybrid encryption.)
  • Signatures: the private key holder signs; anyone verifies with the public key.
  • Key agreement: two parties derive a shared secret from their key pairs (Diffie-Hellman).
symmetric Alice Bob shared key K AES-GCM(K) fast · but how do they share K? asymmetric Alice Bob Bob public Bob private encrypt to public sign with private · verify with public real protocols are hybrid: key agreement (ECDH / ML-KEM) → symmetric AEAD for dataTLS 1.3 · HPKE · Signal · age · envelope encryption with KMS
Symmetric versus asymmetric cryptography. Symmetric uses one shared secret key for both directions and is fast; asymmetric uses a public/private key pair: anyone can encrypt to or verify with the public key, only the private key holder can decrypt or sign. Real protocols combine them: asymmetric to agree or exchange a key, symmetric AEAD for the data.

Algorithms

Family Algorithms Notes
RSA (1977) RSA-OAEP (encryption), RSA-PSS (signatures), PKCS#1 v1.5 (legacy) Security from factoring; keys 2048-bit minimum, 3072+ for long-term; slow key generation, large keys; avoid textbook RSA and PKCS#1 v1.5 encryption (Bleichenbacher padding-oracle attacks)
Elliptic curves ECDSA (P-256, P-384), ECDH, X25519 (key agreement), Ed25519 (EdDSA signatures) Much smaller keys for equal security (256-bit ECC ≈ 3072-bit RSA); Curve25519-based algorithms are designed to be hard to misuse
Post-quantum ML-KEM (FIPS 203, key encapsulation), ML-DSA (FIPS 204, signatures), SLH-DSA (FIPS 205, hash-based signatures) Resistant to quantum computers (below)

Digital signatures

A signature proves that the holder of a private key approved these exact bytes: integrity + authenticity + (with proper key management) non-repudiation. Uses: TLS certificates, JWTs (RS256, ES256, EdDSA), code and container signing (Sigstore), Git commits, software updates, documents.

Pitfalls:

  • ECDSA nonces: each ECDSA signature needs a fresh secret random value; reuse or bias leaks the private key (the PlayStation 3 signing key was recovered this way in 2010). Use deterministic nonces (RFC 6979, standard in good libraries) or Ed25519, which is deterministic by design.
  • Sign canonical bytes: if the verifier re-serialises data differently (JSON key order, whitespace), signatures break or, worse, attackers exploit parsing differences.
  • Verify what was signed and with which key (key IDs bound to trusted keys; never take the algorithm or key from the untrusted message itself: the classic JWT alg: none and algorithm-confusion bugs, chapter 109).
Go
// Go: Ed25519 sign and verify
pub, priv, _ := ed25519.GenerateKey(rand.Reader)
msg := []byte(`{"order":"9817","amount":4999}`)
sig := ed25519.Sign(priv, msg)
fmt.Println(ed25519.Verify(pub, msg, sig))        // true; any change to msg or sig → false

Key exchange and forward secrecy

Diffie-Hellman (1976) lets two parties agree on a shared secret over a public channel: each has a key pair; combining your private key with their public key yields the same secret on both sides. ECDHE with X25519 is the modern standard.

Ephemeral key exchange (new key pairs for every session, the "E" in ECDHE) gives forward secrecy: if a server's long-term private key is stolen later, past recorded sessions can't be decrypted, because their session keys came from ephemeral keys that were deleted. TLS 1.3 requires ephemeral key exchange; older RSA key transport (where the client encrypted the session key to the server's RSA key) had no forward secrecy and is gone from TLS 1.3.

Hybrid encryption

To encrypt data for a recipient's public key, combine:

  1. KEM / key agreement to establish a symmetric key (ephemeral ECDH with the recipient's public key, or ML-KEM encapsulation),
  2. a KDF (HKDF) to derive the AEAD key,
  3. AEAD for the data.

HPKE (Hybrid Public Key Encryption, RFC 9180) standardises exactly this and underpins Encrypted Client Hello, MLS (Messaging Layer Security) and Oblivious HTTP. Tools like age do the same for files.

Certificates and PKI

X.509 certificates

A public key alone doesn't say whose it is. A certificate binds a public key to an identity (a domain name, an organisation, a service), signed by a certificate authority (CA):

  • Subject / Subject Alternative Names (SANs: the DNS names or URIs the certificate is valid for; browsers ignore the Common Name)
  • Public key
  • Issuer, serial number, validity period (notBefore, notAfter)
  • Extensions: key usage, extended key usage (server auth, client auth, code signing), basic constraints (is it a CA?), CRL/OCSP pointers, SCTs
  • The issuer's signature over all of it

The chain of trust

root CAtrust store · offline intermediate CAissues certificates leaf certificateSAN: api.example.com signs signs client verification① chain signatures up to a trusted root② hostname matches SAN · ③ within validity dates④ key usage · ⑤ not revoked · ⑥ CT proof (browsers) CertificateTransparency logspublic, append-only
A certificate chain. The server presents its leaf certificate plus an intermediate; the client builds a path to a root certificate it already trusts in its trust store, verifying each signature, the validity dates, the name in the leaf's SAN, and revocation status. Certificate Transparency logs make every publicly trusted certificate auditable.
  • Trust stores: operating systems, browsers (Mozilla, Chrome Root Program, Apple, Microsoft) and runtimes (Java's cacerts, which may differ from the OS) ship root certificates.
  • Revocation: CRLs and OCSP have long been unreliable (soft-fail); the industry is moving to short-lived certificates instead. Let's Encrypt ended OCSP in 2025 and offers short-lived certificates, and the CA/Browser Forum is reducing maximum public certificate lifetime in steps to 47 days by 2029 (200 days from March 2026). Automate issuance with ACME (Vol. 6 ch. 82).
  • Certificate Transparency (CT): CAs must log publicly trusted certificates to append-only logs; browsers require proof (SCTs). You can monitor CT (crt.sh, Cert Spotter) for certificates issued for your domains that you didn't request.
  • CAA DNS records restrict which CAs may issue for your domain.

Private PKI and mTLS

Internal services use a private CA (AWS Private CA, Google CAS, Vault PKI, step-ca, cert-manager with an issuer, SPIRE for workload certificates) to issue certificates for mutual TLS: both client and server present certificates, giving cryptographic workload identity. Keep root keys offline or in HSMs, issue short-lived leaf certificates automatically, and rotate continuously.

TLS 1.3

TLS (Transport Layer Security) protects data in transit: confidentiality, integrity and server (optionally client) authentication. TLS 1.3 (RFC 8446, 2018) simplified the protocol and removed weak options (RSA key transport, CBC modes, SHA-1, renegotiation, compression):

clientserver ClientHello: versions, ciphers, key_share, SNI, ALPN ServerHello: chosen key_share encrypted from here (handshake keys from ECDHE): EncryptedExtensions · Certificate · CertificateVerify (signature over the transcript) · Finished client verifies chain + signature; sends Finished application data · AEAD (AES-GCM / ChaCha20-Poly1305)
The TLS 1.3 full handshake in one round trip. The client sends key shares with its hello; the server picks parameters, sends its key share, and everything after that, including its certificate and a signature proving possession of the private key, is encrypted. Both sides derive traffic keys from the ephemeral key exchange, giving forward secrecy.

Key points:

  • One round trip (1-RTT) for a full handshake; 0-RTT resumption sends data immediately but that early data is replayable, so only use it for idempotent requests (or disable it).
  • The client sends key shares in its first message; modern browsers and libraries send the hybrid post-quantum group X25519MLKEM768 alongside classical X25519.
  • The certificate is encrypted in TLS 1.3 (privacy); Encrypted Client Hello (ECH) also hides the SNI hostname.
  • CertificateVerify proves the server holds the private key for its certificate (signature over the handshake transcript).
  • Cipher suites are only AEADs: TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256.
  • Configure servers for TLS 1.2 and 1.3 only, HSTS, and modern defaults (Mozilla's SSL configuration generator); test with testssl.sh or SSL Labs.

Application mistakes to avoid: disabling certificate verification (InsecureSkipVerify: true, verify=False, trust-all TrustManagers, rejectUnauthorized: false), even "temporarily" in production code; not checking hostnames; pinning certificates without a rotation plan (prefer pinning to your own CA or not pinning).

Key management and rotation

Strong algorithms are useless if keys leak. Key management covers the lifecycle: generation, storage, distribution, use, rotation, revocation and destruction.

  • Generate keys with a CSPRNG or inside an HSM/KMS; never derive keys from passwords without a proper KDF (Argon2/scrypt/PBKDF2), and use HKDF to derive multiple keys from one secret.
  • Store keys in a KMS or HSM (AWS KMS, Azure Key Vault/Managed HSM, Google Cloud KMS, HashiCorp Vault Transit), not in code, config files, environment variables in images, or databases next to the data.
  • Envelope encryption (Vol. 7 ch. 88): data keys encrypted by a key-encryption key in the KMS.
  • Least privilege on keys: separate keys per purpose, environment and tenant; key policies granting decrypt only to the services that need it; audit every use.
  • Rotation:
  • Why: limit the amount of data under one key, limit exposure if a key leaked unnoticed, meet compliance requirements, and keep rotation a practised routine.
  • How: version keys and store a key ID with every ciphertext or signature (kid in JWTs, key version in KMS ciphertext), so you can decrypt/verify old data while encrypting/signing with the new key. For signature keys, publish the new public key (JWKS) before signing with it, and keep the old one until all its signatures have expired.
  • Re-encryption: rotation of a KMS master key often doesn't require re-encrypting data (old key versions remain available for decryption); re-encrypt or re-wrap data keys when you must retire old versions.
  • Revocation and destruction: disable compromised keys immediately; scheduled deletion (crypto-shredding) to make data unrecoverable.
  • Secrets other than keys (API tokens, database passwords) follow the same lifecycle via secrets managers with automatic rotation.

Post-quantum cryptography

A sufficiently large quantum computer running Shor's algorithm would break RSA and elliptic-curve cryptography (factoring and discrete logarithms), while Grover's algorithm only halves the effective strength of symmetric keys and hashes (so AES-256 and SHA-384+ remain comfortable). Nobody knows when such a machine will exist, but:

  • Harvest now, decrypt later: adversaries can record encrypted traffic today and decrypt it once quantum computers exist, so data that must stay confidential for 10+ years is at risk now.
  • Migrating cryptography across an organisation takes years.

NIST published the first post-quantum standards in August 2024:

Standard Algorithm Use
FIPS 203 ML-KEM (from CRYSTALS-Kyber) Key encapsulation (replacing ECDH/RSA key exchange)
FIPS 204 ML-DSA (from CRYSTALS-Dilithium) Signatures
FIPS 205 SLH-DSA (from SPHINCS+) Hash-based signatures (conservative, large signatures)
(selected 2025) HQC Backup KEM based on different mathematics

Adoption status in 2026: hybrid key exchange (X25519MLKEM768: classical + post-quantum, secure if either holds) is on by default in Chrome, Firefox, Safari, Cloudflare, AWS endpoints, OpenSSL 3.5+, Go 1.24+ and more, so a large share of web TLS traffic is already quantum-resistant against harvest-now-decrypt-later. Post-quantum signatures and certificates are further behind (larger keys and signatures complicate certificates and handshakes). Governments have set migration timelines (e.g. the US NSA's CNSA 2.0 for national security systems, and NIST's plan to deprecate quantum-vulnerable algorithms after 2030 and disallow them after 2035).

What engineers should do now: inventory where cryptography is used (a "cryptographic bill of materials"), prefer libraries and platforms that support hybrid PQ key exchange, design for crypto agility (algorithms and keys identified and swappable, not hard-coded), and keep long-lived secrets on PQ-protected channels.

Common mistakes checklist

Mistake Fix
Non-cryptographic RNG for tokens CSPRNG (SecureRandom, crypto/rand, secrets)
MD5/SHA-1 for security, or fast hash for passwords SHA-256+/BLAKE3 for integrity; Argon2id for passwords
SHA256(key + msg) as a MAC HMAC
Comparing MACs/tokens with == Constant-time comparison
ECB mode, or encryption without authentication AEAD (AES-GCM, ChaCha20-Poly1305)
Nonce reuse Random nonces with key rotation, XChaCha20, or GCM-SIV
Hard-coded keys, keys in Git or images KMS/secret manager, envelope encryption
Disabling TLS verification Fix the trust store; use a proper internal CA
Trusting algorithm/key choice from untrusted input Fixed algorithm allow-lists; keys from trusted configuration
Custom protocols TLS, HPKE, Noise, libsodium boxes

Lab: applied cryptography, measured

Python 3 with cryptography 50.0.1, bcrypt and argon2-cffi, plus OpenSSL 3.0.13, on one core of the lab machine. Timings vary by CPU; the ratios are what matter.

Experiment 1: what password-hash cost buys you

Text
bcrypt cost  8:    17.8 ms  → ~56 guesses/s
bcrypt cost 10:    71.5 ms  → ~14 guesses/s
bcrypt cost 12:   277.9 ms  → ~4 guesses/s
bcrypt cost 14:  1118.8 ms  → ~1 guess/s
argon2id (t=3, m=64 MiB, p=4): 149.3 ms, 64 MiB per guess
md5 single call (incl. warm-up): 53.7 µs; md5 in a tight loop: 448 ns → ~2.2 M guesses/s/core

The bcrypt row doubles per cost step, exactly as designed. The two MD5 numbers are a lesson in measurement: the first call includes interpreter warm-up, and even the 448 ns figure is mostly Python overhead, since native MD5 on a GPU runs billions per second. Choosing a cost: pick the highest your login path tolerates (OWASP's Password Storage Cheat Sheet recommends Argon2id with at least 19 MiB memory and t=2, or bcrypt cost ≥ 10), and store the parameters inside the hash string ($2b$10$…, $argon2id$v=19$m=65536,t=3,p=4$…) so you can raise them later and rehash on next login.

Experiment 2: AEAD rejects tampering and context swaps

AES-256-GCM, message transfer 100 to alice, associated data account:42:

Text
ciphertext 37 bytes (21 plaintext + 16-byte tag)
decrypt untampered:                       transfer 100 to alice
one bit flipped in ciphertext:            InvalidTag
decrypted with associated data account:99: InvalidTag

Associated data is the underused feature: it is not encrypted, but it is authenticated. Binding the record's ID, the tenant or the schema version into it stops an attacker moving a valid ciphertext from one row, tenant or context to another (a "cut-and-paste" attack), which plain encryption allows.

Experiment 3: the cost of a reused nonce

Text
c1 ⊕ c2  : 0000000009080909000000000c0d050f0a
p1 ⊕ p2  : 0000000009080909000000000c0d050f0a   (identical)
p2 recovered from p1: PAY 9999 TO MALLO

GCM is counter mode underneath: ciphertext = plaintext ⊕ keystream(key, nonce). Same key and nonce, same keystream, and it cancels. Worse (not shown), reuse also leaks GCM's authentication subkey, so an attacker can forge valid tags. Real incidents have happened this way (TLS servers that reused GCM nonces were found by the 2016 "Nonce-Disrespecting Adversaries" scan). Defences: random 96-bit nonces from the CSPRNG with key rotation long before 2³² messages per key, deterministic counters persisted carefully, or a nonce-misuse-resistant mode (AES-GCM-SIV) where you can't guarantee uniqueness.

Experiment 4: signatures versus MACs

Text
ECDSA P-256 signature 71 bytes; verify genuine: OK; verify tampered: rejected
Ed25519 signature 64 bytes
HMAC-SHA256 tag 32 bytes; verifiable only by holders of the shared key

A webhook between two companies can use HMAC (both hold the key; neither can later prove to a third party who sent a message). A software release must use a signature: millions of users verify with the public key, and only the publisher can sign.

Experiment 5: why hybrid encryption

Text
RSA-2048 public encrypt:   66 µs/op       RSA-2048 sign:   0.38 ms
RSA-3072 public encrypt:   86 µs/op       RSA-3072 sign:   1.03 ms
                                          RSA-4096 sign:   2.38 ms
ECDSA P-256 sign: 0.05 ms                 RSA-4096 keygen: 670 ms; P-256 keygen: 0.1 ms
AES-256-GCM 1 KiB: 1.8 µs/op (~566 MB/s, through Python)
X25519: both sides derived the same 32-byte secret: True

RSA's private operation grows roughly with the cube of key size (2048→4096 is 6×); elliptic curves are an order of magnitude faster for signing and keys are 32 bytes instead of 256–512. Symmetric encryption is in a different league again (and hardware AES-NI makes it faster still outside Python). So protocols do one public-key operation per session and encrypt the data symmetrically.

Experiment 6: TLS verification, done and undone

A lab CA (P-256) signed a server certificate for tiffin.local with subjectAltName=DNS:tiffin.local. openssl s_server -tls1_3 served it:

Text
client trusts nothing     → TLSv1.3 TLS_AES_256_GCM_SHA384, Verify return code: 21 (unable to verify the first certificate)
client trusts lab CA      → Server Temp Key: X25519, 253 bits; Peer signature type: ECDSA; Verify return code: 0 (ok)
expects evil.local        → Verify return code: 62 (hostname mismatch)
client forces TLS 1.2     → tlsv1 alert protocol version (alert 70)

Note what s_client does by default: it reports a failed verification and carries on. Many libraries behave like that when you pass verify=False, InsecureSkipVerify: true or rejectUnauthorized: false; the session is encrypted, but to whoever answered. Verification has two halves, the chain (signed by a CA you trust, not expired, not revoked) and the name (the certificate is for the host you meant); skipping either one leaves you open to a man-in-the-middle.

The commands:

Shell
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout ca.key -out ca.crt -days 30 -subj "/CN=Tiffin Lab CA"
openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout srv.key -out srv.csr -subj "/CN=tiffin.local"
printf "subjectAltName=DNS:tiffin.local\n" > ext
openssl x509 -req -in srv.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out srv.crt -days 7 -extfile ext
openssl s_server -accept 8443 -cert srv.crt -key srv.key -tls1_3 -www
openssl s_client -connect 127.0.0.1:8443 -servername tiffin.local -CAfile ca.crt -verify_hostname tiffin.local

Try it yourself

  1. Time Argon2id at m=19 MiB, t=2 and m=256 MiB, t=1. Which costs an attacker more, and which costs your login server more under 100 logins per second?
  2. Encrypt 1 MiB with AES-GCM and ChaCha20-Poly1305 and compare throughput. Then check grep -m1 -o aes /proc/cpuinfo; why do phones without AES hardware prefer ChaCha20?
  3. Issue a certificate with only CN=tiffin.local and no subjectAltName. Does modern verification accept it?
  4. Sign a file with Ed25519, change one byte, and verify. Then change the public key by one byte and verify again.

Revision sheet: cryptography foundations

Key ideas

  • Don't invent crypto; use vetted libraries and high-level APIs (libsodium, Tink, cryptography, JCA with care).
  • Pick the tool by the question: hash (integrity), MAC (shared-key authenticity), signature (public verifiability, non-repudiation), AEAD (confidentiality + integrity), key exchange (agreeing keys), slow password hash (storing passwords).
  • Passwords: Argon2id (or bcrypt/scrypt), salted, parameters stored in the hash, rehash on login when you raise cost.
  • AEAD only for new code: AES-GCM or ChaCha20-Poly1305; bind context with associated data; never reuse a nonce under one key.
  • Randomness from the OS CSPRNG for every key, token, nonce and salt.
  • Hybrid: public-key crypto sets up keys; symmetric crypto moves data. Ephemeral ECDH gives forward secrecy.
  • TLS 1.3: ECDHE key exchange, certificate signature, AEAD record protection; verify the chain and the hostname.
  • Key management is the hard part: generate, store (KMS/HSM), rotate, revoke, and use envelope encryption.
  • Post-quantum: ML-KEM (FIPS 203) and ML-DSA (FIPS 204) are standardised; hybrid X25519+ML-KEM key exchange is deployed in browsers; plan crypto-agility now ("harvest now, decrypt later").

Numbers to remember

  • Lab: bcrypt cost 12 ≈ 278 ms; each cost step doubles; MD5 ≈ 448 ns per hash in Python, about 600,000× faster.
  • AES-GCM: 12-byte nonce, 16-byte tag; rotate keys well before 2³² random-nonce messages.
  • X25519 public key 32 bytes; Ed25519 signature 64 bytes; ECDSA P-256 ≈ 70–72 bytes DER.
  • RSA-2048 ≈ 112-bit security, RSA-3072 / P-256 ≈ 128-bit; AES-128 is 128-bit, AES-256 is the post-quantum-comfortable choice.
  • Lab: RSA-4096 sign 2.38 ms vs ECDSA P-256 0.05 ms.

Pitfalls

  • Fast hashes (MD5, SHA-256 alone) for passwords; unsalted hashes.
  • ECB or CBC without a MAC; "encrypt then forget to authenticate".
  • Reusing nonces or IVs; hard-coded keys in source or images.
  • random/Math.random for tokens.
  • Disabling TLS verification "temporarily"; checking the chain but not the hostname.
  • Comparing MACs with == (timing leak); use constant-time compare.
  • Using one key for several purposes instead of deriving separate keys with HKDF.

Glossary

  • AEAD: authenticated encryption with associated data.
  • Nonce: number used once per key.
  • KDF: key derivation function (HKDF for keys, Argon2id for passwords).
  • Forward secrecy: a stolen long-term key doesn't decrypt past sessions.
  • Envelope encryption: data encrypted with a data key, data key encrypted with a master key in a KMS.
  • PKI: the CAs, certificates and revocation that bind public keys to names.