Cryptography Fundamentals: AES-GCM, ChaCha20, RSA/ECC/Ed25519, ECDH, KDFs, HMAC, Signatures, Randomness
"The system must not require secrecy and can be stolen by the enemy without causing trouble." — Auguste Kerckhoffs, La cryptographie militaire, Journal des sciences militaires, 1883 (English rendering by Fabien Petitcolas)
Summary: Cryptography is a small toolbox of primitives (ciphers, AEAD, MACs, signatures, key exchange, KDFs, randomness); each one buys a specific security goal, and almost every real failure comes from using the right primitive the wrong way. Focus: What each primitive guarantees, the rules it needs (nonce uniqueness, key sizes, key separation, constant-time checks), the classic breaks (ECB, nonce reuse, padding oracle, ECDSA nonce reuse) and the Go and Laravel code that uses them correctly. Learning goal: Pick the right primitive for a goal, call it through a vetted library with correct nonces, keys and AAD, version and rotate keys, and recognise a home-made construction before it ships.
This page is the reference for cryptographic primitives as an application developer meets them: the four security goals and which primitive gives which; Kerckhoffs's principle and why you do not roll your own; symmetric encryption (block and stream ciphers, AES, modes ECB, CBC, CTR, GCM, ChaCha20-Poly1305, XChaCha20); authenticated encryption and AAD; nonces, IVs, keys and salts; key sizes and security levels, including the post-quantum standards; RSA, elliptic curves, Ed25519 and ECDSA; Diffie-Hellman, X25519 and forward secrecy; hybrid encryption; MACs versus signatures; KDFs; randomness; key rotation and versioned ciphertexts; and timing attacks. It deliberately leaves four neighbours to their own pages: certificate chains, PKI design and secrets management are in Cryptography, TLS, PKI & Secrets; the TLS handshake on the wire is in TLS in Practice; password hashing (bcrypt, Argon2) and JWT/PASETO signing are in Password Hashing & Signed Tokens; database encryption layers (TDE, column encryption, KMS envelope encryption) are in Encryption at Rest, in Transit & in Use; and a package-by-package Go API walkthrough is in Hashing & Crypto in Go. Checksums and hash functions themselves are in Checksums & Hashing.
Page map
| If you are looking for | Go to |
|---|---|
| Which primitive gives which goal, in one table | Everything in one minute |
| Why not invent your own scheme | Why cryptography is a toolbox, not a project |
| Kerckhoffs, Diffie-Hellman, RSA, AES, GCM, Ed25519, ML-KEM dates | Where it comes from |
| Confidentiality, integrity, authenticity, non-repudiation | Security goals |
| AES, block vs stream, ECB, CBC, CTR, GCM, ChaCha20 | Symmetric encryption and the mode blocks after it |
| AEAD, AAD, encrypt-then-MAC | Authenticated encryption |
| Nonce vs IV vs key vs salt | Nonces, IVs, keys and salts |
| 128 vs 256 bits, RSA sizes, post-quantum | Key sizes and security levels |
| RSA-OAEP/PSS, P-256, Curve25519, Ed25519, ECDSA | Asymmetric cryptography |
| DH, ECDH, X25519, forward secrecy, KEM + DEM | Key exchange, Hybrid encryption |
| HMAC vs signature, HKDF vs Argon2 | MACs vs signatures, KDFs |
CSPRNG, /dev/urandom, UUIDv4 | Randomness |
| Envelope encryption, rotation, versioned ciphertexts | Key hierarchy and rotation |
Timing attacks and hmac.Equal / hash_equals | Constant-time comparison |
Byte layouts, Laravel Crypt internals, library table, error messages | Mechanics |
| Go + Laravel code for each job | Solving the classic problems |
| ECB, IV reuse, MAC-then-encrypt, hard-coded keys… | Common mistakes |
| Error → cause → fix | Troubleshooting |
| Which primitive for which job | Choosing |
| Monolith → microservices → multi-region | In architecture |
| ECB penguin, nonce reuse, padding oracle, speed | Lab |
Everything in one minute
Goals and the primitive that provides each. Every row is unpacked in the concept catalogue.
| Goal | In plain words | Primitive that gives it | Does NOT give it |
|---|---|---|---|
| Confidentiality | Only key holders can read it | Cipher (AES, ChaCha20), best inside an AEAD | Hash, MAC, signature, Base64 |
| Integrity | Any change is detected | AEAD tag, MAC (HMAC), signature | A cipher alone; a plain hash against an attacker |
| Authenticity | It came from someone holding the key | MAC or AEAD (shared key), signature (private key) | Encryption alone |
| Non-repudiation | A third party can prove who signed | Digital signature (Ed25519, ECDSA, RSA-PSS, ML-DSA) | MAC, AEAD: both sides hold the same key |
Use this, not that.
| Job | Use | Not |
|---|---|---|
| Encrypt data with a secret key | AES-256-GCM or XChaCha20-Poly1305 via a library | AES-ECB, AES-CBC without MAC, "XOR with a key" |
| Encrypt to someone's public key | HPKE / age / libsodium crypto_box_seal (X25519 + AEAD) | Raw RSA, RSA PKCS#1 v1.5 encryption |
| Prove a message came from your service to anyone | Ed25519 signature | HMAC (verifiers could forge) |
| Authenticate a webhook between two parties | HMAC-SHA256 + constant-time compare + timestamp | sha256(secret + body), == comparison |
| Turn a shared secret into keys | HKDF with a distinct info per use | Using the raw ECDH output as a key |
| Store passwords | Argon2id / bcrypt (see password hashing) | SHA-256, HKDF, encryption |
| Generate tokens, keys, nonces | crypto/rand, random_bytes(), /dev/urandom | math/rand, mt_rand(), uniqid(), time |
| Compare secrets | hmac.Equal, subtle.ConstantTimeCompare, hash_equals | ==, bytes.Equal, strcmp |
The three numbers you must never confuse.
| Thing | Secret? | Must be unique? | Must be random? | Typical size |
|---|---|---|---|---|
| Key | Yes | Per purpose | Yes (or derived by a KDF) | 16 or 32 bytes symmetric |
| Nonce / IV | No, sent in clear | Yes, per key, forever | GCM: unique (random OK below 2^32 messages); CBC IV: unpredictable | 12 bytes GCM, 24 bytes XChaCha20, 16 bytes CBC |
| Salt | No, stored in clear | Should be | Yes | 16 bytes or more |
The map above is the page in one picture: a cipher alone only hides; an AEAD hides and detects tampering among key holders; only a signature tells a third party who signed; key exchange, KDFs and the random generator produce the keys the others need.
Why cryptography is a toolbox, not a project
Data leaves your control constantly: it crosses networks, sits in backups, lands in logs, is cached by a CDN, and is read by colleagues with database access. Cryptography replaces "keep the whole system secret" with "keep a 32-byte key secret". That is the entire bargain, and Kerckhoffs stated it in 1883: the design may fall into the enemy's hands; only the key must not.
| Symmetric (one shared key) | Asymmetric (key pair) |
|---|---|
| AES, ChaCha20, HMAC, Poly1305 | RSA, ECDH/X25519, Ed25519, ECDSA, ML-KEM, ML-DSA |
| Fast: about 200 ns to seal 1 KiB with AES-GCM on our machine | Slow: 12 µs (Ed25519 sign) to 0.6 ms (RSA-2048 private-key operation) per operation |
| Both sides need the same secret: distribution is the hard part | Public key can be published; only the private key is secret |
| Gives confidentiality, integrity, shared-key authenticity | Gives key agreement, signatures, non-repudiation |
| Used for bulk data | Used to agree or wrap the symmetric key, or to sign |
The analogy we reuse on this page: a shop with a safe, a mail slot and a wax seal. A safe with one combination is symmetric encryption: anyone who knows the combination can open and close it. A tamper-evident bag around what you put in the safe is the MAC/AEAD tag: you see if someone fiddled with it, but anyone with the combination could have sealed the bag. A mail slot in the door is public-key encryption: anyone can drop a letter in, only the owner has the key to the box behind it. A wax seal with the owner's signet ring is a signature: everyone can check it, only the ring holder can make it, and a judge can be shown it. The combination itself must be picked by dice, not by birthdays: that is the random generator.
Three common misunderstandings, up front
- "Encrypted means nobody can change it." Plain AES-CBC or AES-CTR ciphertext can be modified so that it decrypts to something the attacker chose (bit flipping in CTR, padding oracles in CBC). Only an authenticated mode (AEAD) or encrypt-then-MAC detects changes.
- "A secret algorithm is extra security." It is extra risk: nobody reviewed it. Every scheme in this page is public, and its security rests on the key and on following its rules (unique nonces, separate keys, constant-time checks).
- "AES-256 is safe, so my system is safe." AES has not been the weak point in practice; the failures are around it: ECB mode, a repeated nonce, a hard-coded key in Git, a MAC compared with
==, a token frommath/rand, plaintext written to a log.
Kerckhoffs's principle and "don't roll your own" Must-know
In plain words: assume the attacker has your source code and knows the algorithm; the only thing they do not have is the key. And use primitives and protocols that experts have attacked for years, through libraries that already got the details right.
Common misunderstanding: "Don't roll your own" means "don't write a cipher". It also means: don't invent a construction (your own way to combine AES and HMAC, your own token format, your own key exchange). Most published breaks, such as padding oracles in web frameworks, are in constructions built from sound primitives.
Definition: Kerckhoffs's second principle, in Petitcolas's English rendering, says the system "must not require secrecy and can be stolen by the enemy without causing trouble". Claude Shannon later phrased it as "the enemy knows the system" (Shannon's maxim; we read that phrasing via Wikipedia, a secondary source). In engineering terms: security rests on key secrecy plus correct use of reviewed algorithms.
| Layer | Roll your own? | Use instead |
|---|---|---|
| Cipher, hash, curve | Never | AES, ChaCha20, SHA-2/3, BLAKE3, X25519, Ed25519 |
| Mode / construction (cipher + MAC, nonce scheme) | Never | AEAD: AES-GCM, ChaCha20-Poly1305; libsodium secretbox |
| Protocol (handshake, token format, file format) | Almost never | TLS 1.3, HPKE (RFC 9180), age, PASETO, JWT with a fixed algorithm |
| Key management (where keys live, who rotates them) | Yes, this is your job | KMS/HSM/Vault plus your own rotation runbook |
| Calling the library correctly | Yes, this is your job | This page |
Where it comes from
| Year | Event | Why it matters today |
|---|---|---|
| 1883 | Kerckhoffs, La cryptographie militaire | Security must rest on the key, not on a secret design |
| 1949 | Shannon, "Communication Theory of Secrecy Systems" | Mathematical basis of ciphers; "the enemy knows the system" |
| 1976 | Diffie and Hellman, "New Directions in Cryptography" | Public-key key agreement: two parties agree a secret over a public channel |
| 1977 | RSA; DES standardised | First practical public-key encryption and signatures; first standard block cipher |
| 1997 | HMAC, RFC 2104 (February) | The keyed MAC used by webhooks, JWT HS256, TLS 1.2 PRF, HKDF |
| 1998 | Bleichenbacher's attack on RSA PKCS#1 v1.5 encryption | Why RFC 8017 keeps v1.5 "only for compatibility" |
| 2001 | AES, FIPS 197 (published November 26, 2001; updated May 9, 2023) | The block cipher used everywhere today |
| 2002 | Vaudenay's CBC padding oracle (EUROCRYPT 2002, via secondary sources) | Why unauthenticated CBC is broken in practice |
| 2007 | GCM, NIST SP 800-38D (November 2007) | The dominant AEAD; 96-bit IVs; the uniqueness rule |
| 2010 | HKDF, RFC 5869 (May) | Standard way to derive many keys from one secret |
| 2013 | RFC 6979 deterministic ECDSA (August) | Removes the "random k" failure that leaks ECDSA keys |
| 2016 | X25519, RFC 7748 (January); PKCS#1 v2.2, RFC 8017 (November) | Modern key agreement; OAEP and PSS required for new apps |
| 2017 | Ed25519, RFC 8032 (January) | Deterministic, fast, small signatures |
| 2018 | ChaCha20-Poly1305, RFC 8439 (June) | The AEAD for platforms without AES hardware; TLS 1.3 cipher suite |
| 2022 | HPKE, RFC 9180 (February) | Standard hybrid public-key encryption (KEM + KDF + AEAD) |
| 2024 | FIPS 203 ML-KEM and FIPS 204 ML-DSA (August 13, 2024) | First post-quantum KEM and signature standards |
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, the definition, a step-by-step timeline, real scenarios, what each product does, and the fix with code pointers into Solving the classic problems.
Security goals: confidentiality, integrity, authenticity, non-repudiation Must-know
In plain words: confidentiality means outsiders cannot read it; integrity means nobody can change it unnoticed; authenticity means you know it came from a key holder; non-repudiation means the sender cannot later deny it, because a third party can check the proof.
Common misunderstanding: "If it decrypts, it is authentic." With a cipher alone, a modified ciphertext decrypts to modified plaintext without error. Integrity and authenticity need a tag (MAC/AEAD) or a signature.
Definition: FIPS 204 defines the strongest goal in one sentence: digital signatures let the recipient show "a third party that the signature was, in fact, generated by the claimed signatory. This is known as non-repudiation". A MAC cannot do this because the verifier holds the same key and could have produced the tag.
Alice (shop) Mallory (on path) Bob (bank)
1 c = AES-CTR(k, "pay 0010 EUR")
2 ------------- c --------------> flips bits at the digit offset:
c' = c XOR ("0010" XOR "9910")
3 ------------- c' --------------> decrypts "pay 9910 EUR"
4 no error: CTR has no integrity
-- with AES-GCM the same flip fails at step 3: "message authentication failed"Real scenarios: an encrypted cookie role=user flipped to role=adm (CTR/CBC without MAC); a webhook body edited in transit; an audit log where an insider claims "the system made that entry" (needs signatures, not HMAC); a release binary replaced on a mirror (signature on the manifest).
| Product / API | Confidentiality | Integrity + authenticity | Non-repudiation |
|---|---|---|---|
Go crypto/cipher NewCTR, NewCBCEncrypter | Yes | No | No |
Go cipher.NewGCM, x/crypto/chacha20poly1305 | Yes | Yes (shared key) | No |
Go crypto/hmac, PHP hash_hmac | No | Yes (shared key) | No |
Go crypto/ed25519, PHP sodium_crypto_sign_detached | No | Yes | Yes |
Laravel Crypt (AES-256-CBC + HMAC, or AES-GCM) | Yes | Yes (shared APP_KEY) | No |
Fix: state which goals each data flow needs, then pick from Choosing. Code: AEAD with key versions, signatures, HMAC webhooks.
Symmetric encryption: block ciphers, stream ciphers and AES Must-know
In plain words: one secret key both encrypts and decrypts. A block cipher (AES) scrambles exactly one 16-byte block; a mode of operation turns it into something that encrypts messages of any length. A stream cipher (ChaCha20, or AES in CTR mode) produces a long pseudorandom keystream that is XORed with the data.
Common misunderstanding: "AES-256 is the encryption." AES alone encrypts 16 bytes; how you chain blocks (the mode), what you use as IV/nonce, and whether you authenticate the result decide whether the system is secure.
Definition: FIPS 197: "The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt and decrypt data in blocks of 128 bits." AES key sizes: AES-128, AES-192 and AES-256 differ only in key length and round count (10, 12, 14). ChaCha20 (RFC 8439) uses a 256-bit key, a 96-bit nonce and a 32-bit block counter, and is "considerably faster than AES in software-only implementations, making it around three times as fast on platforms that lack specialized AES hardware".
| Kind | Examples | Unit | Needs padding? | Parallel? |
|---|---|---|---|---|
| Block cipher in ECB/CBC | AES-ECB, AES-CBC | 16-byte blocks | Yes (PKCS#7) | ECB both ways; CBC decrypt only |
| Block cipher as a stream (counter) | AES-CTR, AES-GCM | Byte | No | Yes |
| Native stream cipher | ChaCha20, XChaCha20, Salsa20 | Byte | No | Yes |
Fix: never call aes.NewCipher(...).Encrypt on data directly; always go through an AEAD (cipher.NewGCM, chacha20poly1305.New, libsodium). That single rule removes ECB, padding and most IV mistakes.
ECB mode and the penguin Must-know
In plain words: ECB (Electronic Codebook) encrypts each 16-byte block on its own with the same key. Same input block, same output block, every time. Patterns in the data stay visible in the ciphertext; the famous demonstration is an encrypted bitmap of the Linux penguin (Tux) whose outline is still clearly visible.
Common misunderstanding: "ECB is fine for short values." Two users with the same 16-byte prefix (email domains, JSON keys, fixed headers) produce identical ciphertext blocks, which leaks equality and lets an attacker cut and paste blocks between ciphertexts.
Definition: NIST SP 800-38A: "In the ECB mode, under a given key, any given plaintext block always gets encrypted to the same ciphertext block." Go deliberately ships no ECB mode in crypto/cipher; OpenSSL and PHP do (aes-128-ecb).
plaintext "YELLOW SUBMARINE" "YELLOW SUBMARINE"
1 ECB: E(k, block1) = 761a b98c ... a7d9
2 E(k, block2) = 761a b98c ... a7d9 <- identical: the repetition leaks
3 CBC: E(k, block1 XOR IV) = 6fc2 7bcb ... b652
4 E(k, block2 XOR c1) = c062 3d52 ... ac51 <- differentReal scenarios: a "secure" ID scheme that encrypts user IDs with ECB and lets users see which accounts share a value; a legacy payment system exchanging ECB-encrypted fields; the bitmap lab below, where 384 pixel blocks produce exactly 2 distinct ciphertext blocks.
| Library | ECB available? |
|---|---|
Go crypto/cipher | No mode; you would have to loop Block.Encrypt yourself (do not) |
PHP openssl_encrypt | Yes: aes-128-ecb, aes-256-ecb |
Laravel Crypt | No: only aes-128-cbc, aes-256-cbc, aes-128-gcm, aes-256-gcm |
| OpenSSL CLI | Yes: openssl enc -aes-128-ecb |
Fix: use an AEAD. If you need deterministic encryption for lookups, use a blind index (HMAC of the value) next to randomised ciphertext, as shown in database encryption.
CBC and the padding oracle Important
In plain words: CBC (Cipher Block Chaining) XORs each plaintext block with the previous ciphertext block before encrypting, starting with a random IV. It hides repetition, but the last block needs padding (PKCS#7: n bytes of value n), and if a server reveals whether padding was valid, an attacker can decrypt everything without the key.
Common misunderstanding: "CBC with a random IV is secure." It is confidential against passive eavesdroppers. Against an active attacker who can submit modified ciphertexts and watch errors (or timing), unauthenticated CBC falls to a padding oracle. RFC 8017 records the same class of attack for RSA: Bleichenbacher (1998).
Definition: Go's NewCBCEncrypter needs an IV whose length "must be the same as the Block's block size". The padding oracle (Vaudenay, EUROCRYPT 2002; we cite the paper via Wikipedia, which reports later instantiations against SSL, IPsec, JavaServer Faces, Ruby on Rails and ASP.NET) uses the server's "padding valid / invalid" answer to learn one plaintext byte per at most 256 requests.
Attacker Server (AES-CBC, no MAC)
1 take target block C2 and previous block C1
2 send (X, C2) with X = guess for last byte ---> decrypt: P' = D(C2) XOR X
3 <--- "bad padding" (400) or "bad JSON" (500)
4 repeat X = 0..255 until "bad JSON": then P'[15] == 0x01
5 D(C2)[15] = X[15] XOR 0x01; P2[15] = D(C2)[15] XOR C1[15]
6 move to byte 14 with padding 0x02 0x02 ... 16 bytes, 16 blocks: all plaintextReal scenarios: different error messages for "decryption failed" and "invalid data"; a 500 versus a 400; a slower path when padding is valid; legacy TLS CBC suites (RFC 7366 notes that "the MAC-then-encrypt mechanism has been the subject of a number of security vulnerabilities over a period of many years").
| Product | Default | Protected against padding oracles? |
|---|---|---|
Laravel Crypt with AES-256-CBC (13.x default) | Encrypt-then-MAC | Yes: HMAC-SHA256 is checked with hash_equals before openssl_decrypt runs |
Raw openssl_decrypt('aes-256-cbc') | No MAC | No, unless you add encrypt-then-MAC |
Go NewCBCDecrypter | No MAC, no padding helper | No; you write padding yourself |
| TLS 1.3 | No CBC suites at all | Yes |
Fix: AEAD; if CBC is forced on you by a legacy format, encrypt-then-MAC with a separate MAC key, verify the MAC first, and return one generic error for every failure. Lab: padding oracle sketch.
CTR mode Important
In plain words: CTR encrypts a counter (nonce + block number) and XORs the result with the data, turning AES into a stream cipher. Fast, parallel, no padding, and the base of GCM.
Common misunderstanding: "CTR is like GCM without the overhead." It is GCM without the integrity: a flipped ciphertext bit flips the same plaintext bit, and a repeated counter block reuses keystream.
Definition: ciphertext = plaintext XOR AES(k, nonce‖counter). The counter blocks must be unique for the life of the key; NIST SP 800-38D recalls that "the Counter mode requirement ... for the counter blocks to be unique" is the root of GCM's own nonce rule.
Real scenarios: disk and storage encryption formats; the inside of GCM; AES-CTR + HMAC in older protocols (encrypt-then-MAC done by hand).
Fix: use GCM (which is CTR plus GHASH authentication) or ChaCha20-Poly1305.
GCM: AES-GCM, the 96-bit nonce and the 2^32 limit Must-know
In plain words: AES-GCM encrypts with CTR mode and computes a 16-byte authentication tag with GHASH over the AAD and the ciphertext. One call encrypts and authenticates. It needs a 12-byte nonce that is never repeated with the same key.
Common misunderstanding: "A random nonce is always fine." A random 96-bit nonce is fine up to a budget. Go's documentation for NewGCMWithRandomNonce: "A given key MUST NOT be used to encrypt more than 2^32 messages, to limit the risk of a random nonce collision to negligible levels." NIST states the same limit for random IVs: the total number of invocations "shall not exceed" 2^32, "unless an implementation only uses 96-bit IVs that are generated by the deterministic construction" (a counter). Past that, rotate the key or use XChaCha20-Poly1305.
Definition: NIST SP 800-38D recommends that "implementations restrict support to the length of 96 bits" for IVs. With a 96-bit IV, the initial counter block is IV‖0x00000001; any other length is hashed with GHASH first. The hash subkey H is AES(k, 0^128). RFC 5116 on reuse: the inadvertent reuse of a nonce "undermines the confidentiality of the plaintexts protected in those two invocations, and undermines all of the authenticity and integrity protection provided by that key."
Service A (same key k, nonce stuck at 000...000 after a config bug)
1 c1 = GCM(k, n, '{"to":"alice","amount":100}')
2 c2 = GCM(k, n, '{"to":"carol","amount":900}')
3 attacker: c1 XOR c2 = p1 XOR p2 = 00000000000000020d1b0c09000000000000000000000008000000
4 attacker knows p1's template -> p2 = (c1 XOR c2) XOR p1 = '{"to":"carol","amount":900}'
5 attacker also solves for GHASH key H from the two tags -> forges tags for any message (the "forbidden attack")Real scenarios: a nonce counter kept in memory and reset on every deploy; two replicas encrypting with the same key and the same counter sequence; a nonce derived from a timestamp in seconds; a VM snapshot restored and continuing the same counter.
| Product | Nonce handling | Notes |
|---|---|---|
Go cipher.NewGCM | You supply 12 bytes | Standard; prepend the nonce to the ciphertext yourself |
Go cipher.NewGCMWithRandomNonce (1.24+) | Generated and prepended; Overhead() is 28 | 2^32 messages per key |
Go NewGCMWithNonceSize, NewGCMWithTagSize | Non-standard sizes | "Only use this function if you require compatibility" |
PHP openssl_encrypt('aes-256-gcm') | You supply $iv; $tag by reference | tag_length 4–16; keep 16 |
PHP sodium_crypto_aead_aes256gcm_encrypt | You supply 12 bytes | Only if sodium_crypto_aead_aes256gcm_is_available() (hardware AES) |
Laravel Crypt with AES-256-GCM | Random 12-byte IV per value | Tag must be 16 bytes; no AAD |
Fix: random nonces from crypto/rand and a key rotation budget; or a counter that is persisted and partitioned per writer; or XChaCha20-Poly1305. Code: AES-GCM with key versions. Lab: nonce reuse.
ChaCha20-Poly1305 and XChaCha20 Must-know
In plain words: the other mainstream AEAD. ChaCha20 is a stream cipher built only from additions, rotations and XORs (constant-time by design), and Poly1305 is a one-time MAC whose key is taken from the ChaCha20 keystream. XChaCha20 stretches the nonce to 24 bytes so random nonces are safe for practically unlimited messages.
Common misunderstanding: "ChaCha20 is weaker than AES because it is newer." RFC 8439 says ChaCha20 "is designed to provide 256-bit security", and TLS 1.3 offers it alongside AES-GCM. It is the better choice on CPUs without AES instructions (older phones, some ARM boards), and in our benchmark it is still fast where AES hardware exists.
Definition: RFC 8439 gives ChaCha20 a 96-bit nonce and a 32-bit counter, which "limits the use of a single (key,nonce) combination to 2^32 blocks, or 256 GB" (a per-message limit, unlike NIST's per-key GCM limit). On reuse: "If a nonce is repeated, then both the one-time Poly1305 key and the keystream are identical between the messages. This reveals the XOR of the plaintexts". XChaCha20 (Internet-Draft draft-irtf-cfrg-xchacha-03, not an RFC) uses HChaCha20 to derive a subkey from the first 128 bits of a 192-bit nonce; the draft states that random 192-bit nonces allow "2^80 messages to be sent under a single key" at a 2^-32 collision chance, so "users can safely generate a random 192-bit nonce for each message and not worry about nonce-reuse vulnerabilities."
| Construction | Key | Nonce | Tag | Where |
|---|---|---|---|---|
| ChaCha20-Poly1305 (RFC 8439) | 32 B | 12 B | 16 B | TLS 1.3, WireGuard, SSH, Go chacha20poly1305.New |
| XChaCha20-Poly1305 | 32 B | 24 B | 16 B | libsodium (sodium_crypto_aead_xchacha20poly1305_ietf_encrypt, "Preferred" in the PHP manual), Go chacha20poly1305.NewX |
NaCl secretbox (XSalsa20-Poly1305) | 32 B | 24 B | 16 B | Go x/crypto/nacl/secretbox, PHP sodium_crypto_secretbox |
| age payload | 32 B (HKDF from file key) | 12 B counter per 64 KiB chunk | 16 B | age file format (C2SP) |
Fix: if you cannot guarantee nonce uniqueness across many writers, prefer XChaCha20-Poly1305 with random nonces. Code: hard-to-misuse defaults.
Authenticated encryption, AAD and encrypt-then-MAC Must-know
In plain words: an AEAD (Authenticated Encryption with Associated Data) encrypts and authenticates in one call. The "associated data" (AAD) is not encrypted but is covered by the tag: change it and decryption fails. You put context there (record ID, column name, key version, header) so a ciphertext cannot be moved to another place.
Common misunderstanding: "I'll encrypt and then add a SHA-256 of the plaintext." A plain hash is not keyed (anyone can recompute it), and MAC-then-encrypt (MAC on plaintext, then encrypt both) forces the receiver to decrypt before it can check anything, which is exactly what padding oracles exploit. The safe composition is encrypt-then-MAC with an independent key, and an AEAD does it for you.
Definition: Go's cipher.AEAD: Seal "encrypts and authenticates plaintext, authenticates the additional data"; the nonce "must be NonceSize() bytes long and unique for all time, for a given key"; Open requires that the nonce and additional data "match the value passed to Seal". Output length = plaintext length + 16-byte tag.
Four inputs, two outputs. The nonce and the AAD are sent or stored in the clear; the AAD is never inside the ciphertext but changing it breaks the tag. Open either returns the full plaintext or an error, never a partial or unverified result.
| Composition | Who uses it | Verdict |
|---|---|---|
| Encrypt-then-MAC (MAC over IV + ciphertext, separate key) | Laravel Crypt CBC mode (same key for both), IPsec ESP, RFC 7366 for TLS | Safe if MAC is checked first in constant time |
| MAC-then-encrypt | TLS up to 1.2 with CBC suites | Source of padding-oracle class bugs (Lucky Thirteen 2013, POODLE 2014, per Wikipedia) |
| Encrypt-and-MAC (MAC over plaintext, sent alongside) | Some older protocol designs | A deterministic MAC on plaintext leaks plaintext equality |
| AEAD (GCM, ChaCha20-Poly1305) | TLS 1.3, QUIC, WireGuard, age | Default choice |
Fix: use AAD for every value whose meaning depends on context: "users.email:42", a key version byte, a tenant ID. Code: AES-GCM with key versions.
Nonces, IVs, keys and salts Must-know
In plain words: a key is the secret. A nonce ("number used once") or IV (initialisation vector) is a public per-message value that makes two encryptions of the same data look different. A salt is a public per-item random value fed to a KDF or password hash so that equal inputs do not produce equal outputs.
Common misunderstanding: "The IV must be secret" or "I'll reuse the salt as the IV". Neither is secret, but they have different rules: a GCM nonce must never repeat under a key; a CBC IV must also be unpredictable; a salt must be unique per item but its reuse breaks nothing catastrophically.
| Value | Secret? | Rule | Repeated → | Store it | Size |
|---|---|---|---|---|---|
| Symmetric key | Yes | Random 128/256 bits; one key per purpose | n/a | KMS, secret store, never Git | 16/32 B |
| GCM nonce | No | Unique per key, forever | Plaintext XOR leaks, tag forgery | Prepended to ciphertext | 12 B |
| XChaCha20 nonce | No | Unique per key; random is fine | Same as above (but collisions are negligible) | Prepended | 24 B |
| CBC IV | No | Unpredictable (random) per message | Equal prefixes leak equality | Prepended | 16 B |
| CTR initial counter | No | Counter blocks never overlap | Keystream reuse | Prepended | 16 B |
| KDF salt (HKDF) | No | Random if available; may be reused | Weaker extraction only | Next to output or fixed per app | 32 B (HashLen) |
| Password salt | No | Unique per password | Rainbow tables, equal hashes visible | Inside the hash string | 16 B |
| ECDSA per-signature k | Yes | Unique, uniformly random or RFC 6979 | Private key recovered | Never stored | 32 B |
Key sizes and security levels (and post-quantum) Important
In plain words: "128-bit security" means the best known attack costs about 2^128 operations. Symmetric keys give roughly their length in bits; RSA needs much larger keys for the same level; elliptic curves need about twice the bits.
Common misunderstanding: "RSA-2048 and AES-256 are equally strong." NIST SP 800-57 Table 2 puts RSA (k = 2048) at 112 bits, RSA-3072 and P-256 at 128 bits, and AES-256 at 256 bits. The same table warns: "The security-strength estimates will be significantly affected when quantum computing becomes a practical consideration."
| Security strength (bits) | Symmetric | RSA / finite-field DH | Elliptic curve (ECDSA, EdDSA, ECDH) |
|---|---|---|---|
| 112 | (3TDEA, deprecated) | 2048 | 224–255 |
| 128 | AES-128 | 3072 | 256–383 (P-256) |
| 192 | AES-192 | 7680 | 384–511 (P-384) |
| 256 | AES-256 | 15360 | 512+ (P-521) |
Post-quantum, briefly. A large quantum computer would break RSA, finite-field DH and all elliptic-curve schemes (Shor's algorithm), and roughly halve the effective strength of symmetric keys (Grover's algorithm), which is why 256-bit symmetric keys are the long-term default. NIST published FIPS 203 (ML-KEM), a key-encapsulation mechanism that "is believed to be secure, even against adversaries who possess a quantum computer" with parameter sets ML-KEM-512, -768 and -1024, and FIPS 204 (ML-DSA) for signatures, both on August 13, 2024. Go ships crypto/mlkem (ML-KEM-768 and -1024) since 1.24, and from Go 1.24 the crypto/tls default "includes the X25519MLKEM768 hybrid post-quantum key exchange"; age 1.3.0+ offers hybrid post-quantum recipients. The practical step today is "harvest now, decrypt later" protection for long-lived secrets through hybrid key exchange; post-quantum signatures matter later, for long-lived roots of trust.
Asymmetric cryptography: RSA, elliptic curves, Ed25519 and ECDSA Must-know
In plain words: a key pair: a public key you can publish and a private key you guard. Encrypt to the public key, or sign with the private key. RSA is built on factoring; elliptic-curve cryptography (ECC) on discrete logarithms on curves, with much smaller keys.
Common misunderstanding: "Encrypt the file with RSA." RSA encrypts at most a few hundred bytes (key size minus padding) and is about 2,800 times slower than AES-GCM per operation in our measurement (0.62 ms for an OAEP decrypt vs 0.22 µs to seal 1 KiB). Real systems encrypt a random symmetric key with the public key (hybrid encryption).
Definition and rules per algorithm:
| Algorithm | Use | Padding / variant to use | Avoid | Sizes |
|---|---|---|---|---|
| RSA encryption | Wrap a key | RSAES-OAEP: "REQUIRED to be supported for new applications" (RFC 8017) | RSAES-PKCS1-v1_5: "included only for compatibility"; Bleichenbacher | 2048 min, 3072 for 128-bit |
| RSA signature | JWT RS256/PS256, code signing, X.509 | RSASSA-PSS: "REQUIRED in new applications" | PKCS#1 v1.5 signatures only for compatibility (no known attack) | 256–384 B signatures |
| ECDSA P-256 | X.509 certs, ES256 JWT, AWS/GCP KMS keys | RFC 6979 deterministic k, or a CSPRNG k | Reusing or biasing k | 32 B key, 64–72 B signature |
| Ed25519 (EdDSA, RFC 8032) | SSH keys, release signing, PASETO v4, age/minisign | Pure Ed25519 | Exposing the 64-byte private key format confusion | 32 B public key, 64 B signature |
| X25519 (RFC 7748) | Key agreement (TLS 1.3, WireGuard, Signal, age) | Reject all-zero shared secret | Using the raw output as a key | 32 B keys |
| ECDH P-256 | FIPS environments, TLS | Validate points (Go crypto/ecdh does) | Invalid-curve points from untrusted input | 32 B scalar |
Curves. P-256 (secp256r1, NIST) is everywhere in X.509 and FIPS-approved KMS. Curve25519 (RFC 7748, "the prime 2^255 - 19 is recommended" for the ~128-bit level) is used as X25519 for key agreement and as Ed25519 (twisted Edwards form) for signatures; it was designed to be easy to implement in constant time. Curve448/Ed448 gives ~224-bit security. (NIST's table lists key sizes for its own curves; the ~128-bit level of Curve25519 is RFC 7748's statement.)
Ed25519 advantages (RFC 8032): "high performance on a variety of platforms"; "The use of a unique random number for each signature is not required"; "It is more resilient to side-channel attacks"; small keys and signatures; and "EdDSA signatures are deterministic. This protects against attacks arising from signing with bad randomness; the effects of which can, depending on the algorithm, range up to full private key compromise."
ECDSA nonce reuse Important. ECDSA needs a fresh secret value k per signature; RFC 6979 says k "must be chosen randomly and uniformly ... Even slight biases in that process may be turned into attacks". If the same k signs two different messages, anyone with both signatures can solve two linear equations for the private key.
Signer (ECDSA, broken RNG returns the same k) Observer
1 s1 = k^-1 (h1 + r*d) for message 1 -----(r, s1)----->
2 s2 = k^-1 (h2 + r*d) for message 2 -----(r, s2)-----> same r: k was reused
3 k = (h1 - h2) / (s1 - s2)
4 d = (s1*k - h1) / r -> private keyThis is the failure behind the PlayStation 3 signing-key recovery announced by fail0verflow in December 2010 (Sony used a static k) and the August 2013 Android Bitcoin wallet thefts caused by colliding k values from a faulty SecureRandom (both via Wikipedia's ECDSA article, a secondary source). Use Ed25519, or ECDSA through a library that uses RFC 6979 or a hedged random k. Go's crypto/ecdsa is hedged: its signatures "are not deterministic, but entropy is mixed with the private key and the message, achieving the same level of security in case of randomness source failure".
Fix: Ed25519 for new signatures; ECDSA P-256 when a standard or FIPS demands it; RSA-PSS/OAEP only for compatibility (JWT RS256 consumers, legacy HSMs). Code: signatures.
Key exchange: Diffie-Hellman, ECDH, X25519 and forward secrecy Must-know
In plain words: two parties each pick a private number, exchange public values over an open channel, and both compute the same shared secret that an eavesdropper cannot. Diffie-Hellman does it with modular arithmetic; ECDH and X25519 do it on elliptic curves.
Common misunderstanding: "The shared secret is the key." The raw ECDH output is a group element with structure; RFC 7748 implementations must check for the all-zero output, and the bytes must go through a KDF (HKDF) with context before use. And DH alone does not authenticate anyone: without signatures or certificates, a man-in-the-middle runs two exchanges.
Definition: X25519 takes a 32-byte scalar and a 32-byte u-coordinate. Go's crypto/ecdh returns crypto/ecdh: bad X25519 remote ECDH input: low order point when the result would be all zero. Forward secrecy means stealing a long-term key later does not reveal past session keys; you get it when both sides use ephemeral key pairs per session and delete them afterwards (TLS 1.3's ECDHE). Encrypting stored data to a static recipient key cannot have forward secrecy for that recipient.
Client Server
1 a = random scalar; A = a*G ---- A ---->
2 <---- B ---- b = random scalar; B = b*G (+ signature over the transcript)
3 S = a*B S = b*A (same point)
4 keys = HKDF(S, transcript) keys = HKDF(S, transcript)
5 delete a delete b -> forward secrecy| Where | Key exchange | Authenticated by |
|---|---|---|
| TLS 1.3 | ECDHE X25519 / P-256, hybrid X25519MLKEM768 | Certificate signature over the handshake (see TLS in Practice) |
| WireGuard | Noise IK with X25519 | Static public keys configured on both ends |
| SSH | curve25519-sha256, sntrup761x25519 | Host key signature, user key |
| age | X25519 recipient, ephemeral sender key | Not sender-authenticated (anyone can encrypt to you) |
Hybrid encryption: KEM + DEM Must-know
In plain words: to encrypt to someone's public key, generate a fresh symmetric key, encrypt the data with an AEAD (fast), and send the symmetric key "encapsulated" for the recipient's public key (slow but tiny). Every serious system does this: TLS, PGP, age, HPKE, S/MIME, cloud KMS envelope encryption.
Common misunderstanding: "Hybrid means RSA-encrypting the AES key." That is the traditional form. RFC 9180 describes the modern one: "The traditional combination has been 'encrypt the symmetric key with the public key.' 'Hybrid' public key encryption (HPKE) schemes, specified here, take a different approach: 'generate the symmetric key and its encapsulation with the public key.'" With X25519 the encapsulation is an ephemeral public key, and the symmetric key comes out of ECDH + HKDF.
Steps 1–4 run on the sender with only the recipient's public key; steps 5–7 on the recipient. Because the HKDF input binds both public keys, a ciphertext cannot be re-targeted to another recipient key, and because the AES key is used once, the fixed nonce is safe.
| Scheme | KEM | KDF | AEAD | Notes |
|---|---|---|---|---|
| HPKE base mode (RFC 9180) | DHKEM(X25519, HKDF-SHA256) or DHKEM(P-256, HKDF-SHA256) | HKDF-SHA256 | AES-128-GCM, AES-256-GCM, ChaCha20Poly1305 | Used by TLS ECH, MLS |
| age | X25519 (or hybrid ML-KEM-768 + X25519 in 1.3.0+) | HKDF-SHA-256 | ChaCha20-Poly1305, 64 KiB chunks | File encryption CLI and Go library |
libsodium crypto_box_seal | X25519 ephemeral | libsodium internal | XSalsa20-Poly1305 | "Anonymous public-key encryption" (PHP manual) |
| Cloud KMS envelope | KMS-held key wraps a data key | n/a | AES-GCM data key | See envelope encryption |
| Our example (code) | X25519 ephemeral | HKDF-SHA256, info binds both keys | AES-256-GCM | Teaching shape, not a standard format |
MACs vs signatures: who can verify Must-know
In plain words: a MAC (HMAC-SHA256, Poly1305) is a tag made and checked with the same secret key. A signature is made with a private key and checked with the public key. So a MAC can be verified only by parties who could also forge it; a signature can be verified by anyone and forged by no one but the signer.
Common misunderstanding: "HMAC is a signature." It is often called "signing" (webhook "signatures", JWT HS256, Laravel signed URLs), but every verifier holds the signing key. A leaked verification key on any consumer lets the attacker mint valid messages for all of them.
Definition: RFC 2104: HMAC is "a mechanism for message authentication using cryptographic hash functions", used "between two parties that share a secret key". Go's crypto/hmac: "The receiver verifies the hash by recomputing it using the same key", and "Receivers should be careful to use Equal to compare MACs in order to avoid timing side-channels".
| Property | HMAC-SHA256 | Ed25519 signature |
|---|---|---|
| Keys | One shared secret | Private (signer) + public (everyone) |
| Who can verify | Key holders only | Anyone with the public key |
| Who can forge | Every verifier | Only the private-key holder |
| Non-repudiation | No | Yes |
| Speed | Hash speed (not benchmarked here) | 12 µs sign, 25 µs verify in our run |
| Typical use | Webhooks between two parties, cookies, signed URLs, JWT HS256 | Releases, JWT EdDSA/ES256 to many consumers, audit logs, SSH |
Truncated MACs. RFC 2104 allows outputting only the leftmost t bits and recommends t "be not less than half the length of the hash output ... and not less than 80 bits". Never truncate below 128 bits for new designs, and never compare only a prefix.
Hashing, recap Good to know
A cryptographic hash (SHA-256, SHA-3, BLAKE3) is keyless: it gives integrity against accidents and a fingerprint, not authenticity, because an attacker who changes the data recomputes the hash. sha256(secret + message) is not a MAC (length-extension on SHA-256); use HMAC. Collision and preimage resistance, CRC vs SHA, and content addressing are in Checksums & Hashing.
KDFs: HKDF for keys, slow KDFs for passwords, domain separation Must-know
In plain words: a key derivation function turns some input secret into one or more keys of the right length. HKDF does it for secrets that already have high entropy (an ECDH output, a master key). Password KDFs (PBKDF2, scrypt, Argon2) do it for low-entropy passwords and are deliberately slow.
Common misunderstanding: "HKDF a password and it becomes a strong key." RFC 5869: "The extract step in HKDF can concentrate existing entropy but cannot amplify entropy"; for passwords "a main goal is to slow down dictionary attacks using two ingredients: a salt value, and the intentional slowing of the key derivation computation", which HKDF does not have.
Definition: HKDF follows "the 'extract-then-expand' paradigm": PRK = HMAC-Hash(salt, IKM), then expand with info. The info input's "main objective is to bind the derived key material to application- and context-specific information"; it "may prevent the derivation of the same keying material for different contexts". That is domain separation: one master secret, many independent keys, each labelled by purpose.
master key (32 B, from KMS)
1 k_enc = HKDF(master, salt, info="app:v1:encrypt:users.email", 32)
2 k_mac = HKDF(master, salt, info="app:v1:blind-index:users.email", 32)
3 k_cookie= HKDF(master, salt, info="app:v1:cookie", 32)
4 -> leaking k_cookie (say, via a debug endpoint) reveals nothing about k_enc or k_mac| KDF | Input | Cost knob | Where |
|---|---|---|---|
| HKDF (RFC 5869) | High-entropy secret | None (fast) | TLS 1.3 key schedule, HPKE, age, Signal; Go crypto/hkdf (1.24+); PHP hash_hkdf |
| PBKDF2 | Password | Iterations | Legacy, FIPS; Go crypto/pbkdf2 (1.24+) |
| scrypt | Password | N, r, p (memory-hard) | Go x/crypto/scrypt, PHP sodium pwhash_scryptsalsa208sha256 |
| Argon2id (RFC 9106) | Password | Memory, iterations, parallelism | Go x/crypto/argon2, PHP password_hash(PASSWORD_ARGON2ID), Laravel Hash |
| KMAC / SP 800-108 KDFs | High-entropy secret | None | FIPS environments, HSMs |
Watch the argument order: Go hkdf.Key(hash, secret, salt, info, length) vs PHP hash_hkdf(algo, key, length, info, salt). Password storage itself is in Password Hashing & Signed Tokens.
Randomness: CSPRNG vs math/rand Must-know
In plain words: keys, nonces, salts, tokens and session IDs must come from a cryptographically secure random number generator (CSPRNG) seeded by the operating system. A normal PRNG (math/rand, mt_rand) is statistically random but predictable: see a few outputs, or know the seed, and you know them all.
Common misunderstanding: "/dev/random is more secure than /dev/urandom." The Linux man page: "The /dev/random interface is considered a legacy interface, and /dev/urandom is preferred and sufficient in all use cases, with the exception of applications which require randomness during early boot time; for these applications, getrandom(2) must be used instead". Modern runtimes already call getrandom(2).
Definition: Go's crypto/rand.Reader uses getrandom(2) on Linux, arc4random_buf(3) on macOS, ProcessPrng on Windows; rand.Read "never returns an error, and always fills b entirely"; rand.Text returns a base32 string with "at least 128 bits of randomness". PHP's random_bytes uses getrandom() then /dev/urandom on Linux. UUIDs: RFC 9562 says implementations "SHOULD utilize a cryptographically secure pseudorandom number generator (CSPRNG)" and that UUIDs "MUST NOT be used as security capabilities (identifiers whose mere possession grants access)". A UUIDv4 has 122 random bits, but use a 32-byte token for anything that grants access.
Service (Go math/rand seeded with time.Now().Unix() at start)
1 10:00:00 process starts, seed = 1764064800
2 10:00:05 reset token for alice = r.Uint64()
3 attacker: requests own reset at 10:00:06, sees his token, brute-forces seeds near the start time
4 attacker: replays the generator from the found seed -> alice's token| Language / tool | CSPRNG | Not for secrets |
|---|---|---|
| Go | crypto/rand.Read, rand.Text, rand.Int | math/rand, math/rand/v2 (even ChaCha8 source when seeded predictably) |
| PHP / Laravel | random_bytes, random_int, Str::random (built on random_bytes), Str::uuid (v4) | rand, mt_rand, uniqid, str_shuffle, lcg_value |
| Shell | openssl rand -hex 32, head -c 32 /dev/urandom | $RANDOM |
| Linux kernel | getrandom(2), /dev/urandom | n/a |
Seeding mistakes: forking a process after seeding a user-space CSPRNG (both children produce the same stream; RFC 9562 warns to reseed "upon state changes, such as process forks"); VM snapshots restored with the same RNG state; containers or embedded devices generating keys at first boot before the kernel pool is ready; tests replacing the generator and the replacement leaking into production. Code: tokens.
Envelope encryption and the key hierarchy Important
In plain words: encrypt data with a data encryption key (DEK); encrypt the DEK with a key encryption key (KEK) held in a KMS or HSM; store the wrapped DEK next to the data. Rotating the KEK means re-wrapping small DEKs, not re-encrypting terabytes.
Common misunderstanding: "The KMS encrypts my data." It usually encrypts only keys (it has request size limits); your service does the bulk AEAD with the DEK in memory. The full treatment (KMS, HSM, BYOK, Vault transit, crypto-shredding) is in Envelope encryption: DEK and KEK; this page owns only the primitives: the DEK is an AEAD key, the wrap is an AEAD or RSA-OAEP/KEM, and every level carries a key ID.
Key rotation and versioned ciphertexts Must-know
In plain words: every ciphertext should say which key made it (a version byte or key ID). Then you can add a new key, encrypt new data with it, keep decrypting old data with old keys, re-encrypt in the background, and finally retire the old key.
Common misunderstanding: "Rotation means changing APP_KEY." Without a key identifier, the decrypter has to guess. Laravel's APP_PREVIOUS_KEYS does exactly that: on decrypt it tries the current key "and if decryption fails using the current key, Laravel will try all previous keys until one of the keys is able to decrypt the value". It works, but costs one MAC (CBC) or one decryption attempt (GCM) per key, and there is no way to find which rows still use an old key except by trying.
Definition: a versioned ciphertext is version ‖ nonce ‖ ciphertext ‖ tag, with the version also in the AAD so it cannot be relabelled. The decrypter fails closed on an unknown version.
Day 0 keys {1}, current = 1 all rows: 0x01...
1 Day 30 keys {1,2}, current = 2 new writes: 0x02...; reads accept 1 and 2
2 Day 30+ background job: SELECT ... WHERE get_byte(email_enc, 0) = 1 LIMIT 1000 -> decrypt(v1) -> encrypt(v2) -> UPDATE
3 Day 35 count of version-1 rows = 0, verified on replicas and backups policy decided
4 Day 36 remove key 1 from the ring; decrypting an old 0x01 blob now fails loudly: "unknown key version: 1"-- PostgreSQL: track progress of a rotation (first byte of the bytea is the key version)
SELECT get_byte(email_enc, 0) AS key_version, count(*)
FROM users
GROUP BY 1
ORDER BY 1;
-- Batch to re-encrypt in the application (Go/Laravel decrypt with v1, encrypt with v2)
SELECT id, email_enc
FROM users
WHERE get_byte(email_enc, 0) = 1
ORDER BY id
LIMIT 1000;| Product | Key ID in ciphertext? | Rotation model |
|---|---|---|
Our Keyring / VersionedEncrypter | Yes, 1 byte, authenticated | Add key, switch current, re-encrypt, retire |
Laravel Crypt + APP_PREVIOUS_KEYS | No | Try each key; sessions survive rotation |
| HashiCorp Vault transit | Yes (vault:v1:... prefix) | Rotate creates a new version; existing values "can then be rewrapped"; min_decryption_version archives old versions |
Code: AES-GCM with key versions. Cryptoperiods and re-encryption at database scale: Rotation, re-encryption and the cryptoperiod.
Constant-time comparison and timing attacks Must-know
In plain words: a normal string comparison stops at the first different byte. If an attacker can measure how long your server takes to reject a MAC, they learn how many leading bytes they got right and can guess the tag one byte at a time.
Common misunderstanding: "Network jitter hides microseconds." Statistical attacks average many requests; RFC 8439 states that if comparison timing "reveals how long a prefix of the calculated and received tags is identical, the number of messages can be reduced significantly. For this reason, with online protocols, implementation MUST use a constant-time comparison function rather than relying on optimized but insecure library functions such as the C language's memcmp()."
Attacker Server (compares with ==)
1 tag = 00 00 00 ... 00 ----> first byte differs: reject after 1 byte (t = 100 ns)
2 tag = 8f 00 00 ... 00 ----> first byte matches: reject after 2 bytes (t = 104 ns)
3 keep 8f, vary byte 2 ... the slowest guess is the right one
4 256 x 32 guesses (x repetitions for noise) instead of 2^256| Language | Constant-time compare | Not constant-time |
|---|---|---|
| Go | hmac.Equal, subtle.ConstantTimeCompare | == on strings, bytes.Equal |
| PHP | hash_equals($known, $user) ("Timing attack safe string comparison") | ==, ===, strcmp |
| Laravel | Crypt uses hash_equals for the MAC; UrlGenerator signed-URL checks use hash_equals | Comparing tokens in your own code with === |
| Node / Python (for reference) | crypto.timingSafeEqual, hmac.compare_digest | ===, == |
Fix: compare MACs, tokens, API keys and reset codes with the constant-time function; better, look tokens up by a hash of the token (so the comparison is on a non-secret index) and compare the rest in constant time. Code: HMAC webhooks.
Mechanics
AES-GCM inside: CTR + GHASH Important
- H = AES(k, 0^128): the GHASH key. NIST: "the hash subkey for the GHASH function is generated by applying the block cipher to the 'zero' block."
- J0 = IV ‖ 0x00000001 when the IV is 96 bits (NIST: "the padding string" 0^31‖1 "is appended to the IV"); other lengths are GHASHed, which is slower and is why 12 bytes is the standard.
- Ciphertext = plaintext XOR AES(k, J0+1), AES(k, J0+2), …
- S = GHASH_H(AAD padded ‖ ciphertext padded ‖ len(AAD) ‖ len(C)); tag = MSB_t(AES(k, J0) XOR S).
- Decrypt recomputes the tag and compares in constant time before returning anything.
Repeating (k, IV) repeats the keystream (confidentiality lost) and gives two equations in the unknown H, which lets an attacker solve for H and forge tags. That is why the IV rule is "almost as important" as key secrecy, in NIST's words: "For GCM, the requirement in Sec. 5.2.1 for the uniqueness of the IVs is almost as important, although not as obvious."
ChaCha20-Poly1305 inside Good to know
The ChaCha20 state is 16 32-bit words: 4 constants, 8 key words, 1 block counter, 3 nonce words; 20 rounds of add-rotate-XOR produce a 64-byte keystream block. Block 0 generates the one-time Poly1305 key; data is encrypted from counter 1. Poly1305 evaluates a polynomial over the AAD and ciphertext modulo 2^130 − 5. RFC 8439: "The operations used in ChaCha20 are all additions, XORs, and fixed rolls. All of these can and should be implemented in constant time."
Byte layouts and hex dumps Must-know
Versioned AES-256-GCM value (from go run ./aeadkeys, macOS arm64, Go 1.27.4; random each run):
00000000 01 4c 63 cc 5a 2f 24 d6 5a 09 a3 0a df 6c 53 0f |.Lc.Z/$.Z....lS.|
00000010 22 d3 2a d0 49 62 d5 a9 e1 7b 11 a9 13 ed 42 36 |".*.Ib...{....B6|
00000020 00 18 08 1a 67 4e 15 a6 40 38 6e d7 |....gN..@8n.|
-> 0x01 = key version | next 12 bytes = nonce | next 15 bytes = "ann@example.com" encrypted | last 16 bytes = tag
-> 1 + 12 + 15 + 16 = 44 bytes (0x2c)ECB vs CBC on repeated input (LibreSSL 3.3.6, key 00..0f):
$ printf "YELLOW SUBMARINEYELLOW SUBMARINE" | openssl enc -aes-128-ecb -nopad -K 000102030405060708090a0b0c0d0e0f | xxd
00000000: 761a b98c 7086 c509 261f 322c b3ff a7d9 v...p...&.2,....
00000010: 761a b98c 7086 c509 261f 322c b3ff a7d9 v...p...&.2,....
$ printf "YELLOW SUBMARINEYELLOW SUBMARINE" | openssl enc -aes-128-cbc -nopad -K 000102030405060708090a0b0c0d0e0f -iv 0f0e0d0c0b0a09080706050403020100 | xxd
00000000: 6fc2 7bcb 0631 3107 af0a b781 a7f7 b652 o.{..11........R
00000010: c062 3d52 c8bc acf5 2f8c a12e f5a0 ac51 .b=R..../......QPKCS#7 padding seen from the inside (decrypt without removing padding): "hi" plus 14 bytes of 0x0e.
$ printf "hi" | openssl enc -aes-128-cbc -K 000102030405060708090a0b0c0d0e0f -iv 00000000000000000000000000000000 \
| openssl enc -d -aes-128-cbc -nopad -K 000102030405060708090a0b0c0d0e0f -iv 00000000000000000000000000000000 | xxd
00000000: 6869 0e0e 0e0e 0e0e 0e0e 0e0e 0e0e 0e0e hi..............Hybrid message: 32-byte ephemeral X25519 public key, ciphertext, 16-byte tag: message: 69 bytes = 32 ephemeral pub + 21 ciphertext + 16 tag.
Sizes to recognise in hex: 16 B AES-128 key / GCM tag / CBC IV; 12 B GCM nonce; 24 B XChaCha20 / secretbox nonce; 32 B AES-256 key, X25519 and Ed25519 public keys, HMAC-SHA256 output; 64 B Ed25519 signature (and libsodium's Ed25519 secret key = seed + public key); 256 B RSA-2048 signature or OAEP ciphertext.
Laravel Crypt, exactly as 13.x implements it Must-know
Read from Illuminate/Encryption/Encrypter.php and config/app.php on the 13.x branch:
| Aspect | Behaviour |
|---|---|
| Configured cipher | config/app.php: 'cipher' => 'AES-256-CBC'; the docs: "All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher" |
| Supported ciphers | aes-128-cbc, aes-256-cbc, aes-128-gcm, aes-256-gcm (constructor default argument is aes-128-cbc; the app config overrides it) |
| Key | APP_KEY, raw length must be 16 or 32 bytes for the cipher; php artisan key:generate uses random_bytes |
| IV | random_bytes(openssl_cipher_iv_length(...)): 16 bytes for CBC, 12 for GCM |
| CBC integrity | hash_hmac('sha256', $iv.$value, $key) over the base64 IV and base64 ciphertext, with the same key as encryption; checked with hash_equals before decrypting (encrypt-then-MAC) |
| GCM integrity | mac field is ''; the 16-byte tag is in tag; a tag of another length is rejected; no AAD is passed |
| Payload | base64(json_encode(['iv','value','mac','tag'])) |
| Serialisation | encrypt() calls serialize(), encryptString() does not |
| Rotation | APP_PREVIOUS_KEYS (comma-separated); encryption uses APP_KEY; decryption tries every key; no key ID in the payload |
| Errors | DecryptException: "The payload is invalid.", "The MAC is invalid.", "Could not decrypt the data."; RuntimeException "Unsupported cipher or incorrect key length" |
| Eloquent | encrypted, encrypted:array, encrypted:collection, encrypted:object casts; column must be TEXT or larger; not searchable |
So Laravel Crypt is a sound encrypt-then-MAC construction in its default CBC mode, and an AEAD when you set 'cipher' => 'AES-256-GCM'. What it does not give you: AAD/context binding (an encrypted value can be copied from one row to another), key IDs, or a nonce budget per key (random 96-bit IVs in GCM mode, so the 2^32-messages-per-key guidance applies to busy apps).
Libraries per language Important
| Job | Go stdlib / x/crypto | PHP / Laravel | CLI |
|---|---|---|---|
| AES-GCM | crypto/aes + cipher.NewGCM, NewGCMWithRandomNonce | openssl_encrypt('aes-256-gcm'), sodium_crypto_aead_aes256gcm_* (if hardware), Crypt with GCM cipher | openssl enc does not support AEAD modes; use age or a script |
| ChaCha20-Poly1305 / XChaCha20 | x/crypto/chacha20poly1305 New, NewX | sodium_crypto_aead_chacha20poly1305_ietf_*, sodium_crypto_aead_xchacha20poly1305_ietf_* | age |
| Secret box (hard to misuse) | x/crypto/nacl/secretbox | sodium_crypto_secretbox | n/a |
| Public-key box | x/crypto/nacl/box (Seal, SealAnonymous) | sodium_crypto_box, sodium_crypto_box_seal | age |
| X25519 / ECDH | crypto/ecdh | sodium_crypto_scalarmult, sodium_crypto_kx_* | openssl pkeyutl -derive (OpenSSL 3) |
| Ed25519 | crypto/ed25519 | sodium_crypto_sign_detached, _verify_detached | ssh-keygen -t ed25519, openssl genpkey -algorithm ed25519 (OpenSSL 3; LibreSSL 3.3.6 says "Algorithm ed25519 not found") |
| ECDSA / RSA | crypto/ecdsa, crypto/rsa (SignPSS, EncryptOAEP) | openssl_sign, openssl_public_encrypt with OPENSSL_PKCS1_OAEP_PADDING | openssl pkeyutl |
| HMAC | crypto/hmac + hmac.Equal | hash_hmac + hash_equals | openssl dgst -sha256 -hmac |
| HKDF | crypto/hkdf (1.24+), x/crypto/hkdf | hash_hkdf | openssl kdf (OpenSSL 3) |
| Random | crypto/rand | random_bytes, random_int, Str::random | openssl rand, /dev/urandom |
| Post-quantum | crypto/mlkem (1.24+) | none in core PHP 8.4 | age 1.3.0+ -pq keys |
| File encryption | filippo.io/age | shell out to age, or sodium secretstream | age |
Error messages you will see Must-know
| Message | Where | Meaning |
|---|---|---|
cipher: message authentication failed | Go AEAD.Open | Wrong key, wrong nonce, wrong AAD, or tampered data; never "partially decrypted" |
crypto/aes: invalid key size 20 | Go aes.NewCipher | Key is not 16, 24 or 32 bytes (often a hex/base64 string passed as raw bytes) |
crypto/ecdh: bad X25519 remote ECDH input: low order point | Go PrivateKey.ECDH | Malicious or corrupt peer key producing the all-zero secret |
crypto/ecdh: invalid public key | Go NewPublicKey | Wrong length or not on the curve |
crypto/rsa: decryption error | Go DecryptOAEP | Wrong key or label, tampered ciphertext; deliberately generic |
openssl_decrypt(): ... returns false | PHP | Same as Go's auth failure for GCM; for CBC without MAC it may return garbage instead |
The MAC is invalid. | Laravel DecryptException (CBC) | Wrong APP_KEY / missing previous key, or tampered payload |
Could not decrypt the data. | Laravel (GCM or decrypt failure) | Wrong key or tampered payload |
The payload is invalid. | Laravel | Not base64 JSON with iv, value, mac, or IV of wrong length |
Unsupported cipher or incorrect key length. | Laravel boot | APP_KEY missing its base64: prefix or wrong length for the cipher |
SodiumException on encrypt | PHP sodium | Nonce or key of the wrong length: "If nonce has a length of bytes different than SODIUM_CRYPTO_SECRETBOX_NONCEBYTES (24 bytes), a SodiumException will be thrown" |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Encrypt a field in the database | AES-256-GCM with versioned key ring and AAD | version + nonce + ct + tag, AAD = version + "table.column:id" | Rotation without guessing; copy-paste between rows detected | Not searchable (add a blind index) |
| Encrypt for a party that has only published a public key | Hybrid: X25519 + HKDF + AEAD (or HPKE / age / crypto_box_seal) | Ephemeral key per message | Only recipient decrypts; fast for big data | No sender authentication unless you also sign |
| Prove origin to many consumers | Ed25519 signature | Sign canonical bytes; distribute the public key | Consumers cannot forge | Key distribution and revocation |
| Authenticate webhooks between two parties | HMAC-SHA256 over timestamp + body | Constant-time compare, tolerance window | Simple, fast | Shared secret on both sides |
| Tokens and keys | CSPRNG, 32 bytes | crypto/rand, random_bytes | Unguessable | Store only a hash of long-lived tokens |
| Default encryption with fewest footguns | libsodium secretbox / XChaCha20-Poly1305, Laravel Crypt | Random 24-byte nonces | No nonce budgeting | Interop with non-sodium systems |
Encrypt a field with AES-GCM and key versions
The Go Keyring writes version ‖ nonce ‖ ciphertext ‖ tag, authenticates the version byte and a record context as AAD, fails closed on unknown versions and offers Rotate. The PHP class is the same construction with openssl_encrypt (same layout, not a tested interop pair). Track progress with the SQL in Key rotation.
// Package main shows AES-256-GCM with a versioned key ring.
// Ciphertext layout: version (1 byte) | nonce (12 bytes) | ciphertext | tag (16 bytes).
// The version byte and a record context are authenticated as AAD, so a
// ciphertext cannot be moved to another row or relabelled with another key.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log"
)
var errUnknownVersion = errors.New("unknown key version")
// Keyring holds every key that may still decrypt, and the one that encrypts.
type Keyring struct {
current byte
keys map[byte][]byte // version -> 32-byte key (from a KMS or secret store)
}
func (k *Keyring) aead(version byte) (cipher.AEAD, error) {
key, ok := k.keys[version]
if !ok {
return nil, fmt.Errorf("%w: %d", errUnknownVersion, version)
}
block, err := aes.NewCipher(key) // 32-byte key selects AES-256
if err != nil {
return nil, err
}
return cipher.NewGCM(block) // 12-byte nonce, 16-byte tag
}
// Encrypt seals plaintext under the current key. context is e.g. "users.email:42".
func (k *Keyring) Encrypt(plaintext []byte, context string) ([]byte, error) {
gcm, err := k.aead(k.current)
if err != nil {
return nil, err
}
out := make([]byte, 1+gcm.NonceSize(), 1+gcm.NonceSize()+len(plaintext)+gcm.Overhead())
out[0] = k.current
rand.Read(out[1:]) // random 96-bit nonce; crypto/rand.Read never fails
aad := append([]byte{k.current}, context...)
return gcm.Seal(out, out[1:1+gcm.NonceSize()], plaintext, aad), nil
}
// Decrypt picks the key named by the version byte and fails closed on anything else.
func (k *Keyring) Decrypt(blob []byte, context string) ([]byte, error) {
if len(blob) < 1+12+16 {
return nil, errors.New("ciphertext too short")
}
gcm, err := k.aead(blob[0])
if err != nil {
return nil, err
}
nonce, sealed := blob[1:1+gcm.NonceSize()], blob[1+gcm.NonceSize():]
aad := append([]byte{blob[0]}, context...)
return gcm.Open(nil, nonce, sealed, aad)
}
// Rotate re-encrypts a value under the current key if it is on an older one.
func (k *Keyring) Rotate(blob []byte, context string) ([]byte, bool, error) {
if len(blob) > 0 && blob[0] == k.current {
return blob, false, nil
}
pt, err := k.Decrypt(blob, context)
if err != nil {
return nil, false, err
}
nb, err := k.Encrypt(pt, context)
return nb, err == nil, err
}
func newKey() []byte {
b := make([]byte, 32)
rand.Read(b)
return b
}
func main() {
ring := &Keyring{current: 1, keys: map[byte][]byte{1: newKey()}}
ct, err := ring.Encrypt([]byte("ann@example.com"), "users.email:42")
if err != nil {
log.Fatal(err)
}
fmt.Print(hex.Dump(ct))
// Wrong context (the value was copied to user 43): authentication fails.
if _, err := ring.Decrypt(ct, "users.email:43"); err != nil {
fmt.Println("moved to another row:", err)
}
// Rotation: add key 2, make it current, old ciphertexts still open.
ring.keys[2], ring.current = newKey(), 2
rotated, changed, err := ring.Rotate(ct, "users.email:42")
if err != nil {
log.Fatal(err)
}
pt, _ := ring.Decrypt(rotated, "users.email:42")
fmt.Printf("rotated=%v version=%d plaintext=%q\n", changed, rotated[0], pt)
// Retire key 1 only after every row is on version 2.
delete(ring.keys, 1)
if _, err := ring.Decrypt(ct, "users.email:42"); err != nil {
fmt.Println("old blob after retirement:", err)
}
}<?php
namespace App\Support\Crypto;
use RuntimeException;
/**
* AES-256-GCM with a versioned key ring, the same layout as the Go example:
* version (1 byte) | nonce (12 bytes) | ciphertext | tag (16 bytes).
* The version byte and a record context are authenticated as AAD.
*
* config/crypto.php:
* 'current' => 2,
* 'keys' => [1 => env('FIELD_KEY_V1'), 2 => env('FIELD_KEY_V2')], // base64, 32 bytes each
*/
final class VersionedEncrypter
{
private const CIPHER = 'aes-256-gcm';
private const NONCE = 12;
private const TAG = 16;
/** @param array<int, string> $keys version => raw 32-byte key */
public function __construct(private int $current, private array $keys)
{
foreach ($keys as $v => $key) {
if (strlen($key) !== 32 || $v < 1 || $v > 255) {
throw new RuntimeException("Key version {$v} must be 1..255 and 32 bytes.");
}
}
}
public static function fromConfig(): self
{
$keys = array_map(fn (string $k) => base64_decode($k, true), config('crypto.keys'));
return new self((int) config('crypto.current'), $keys);
}
public function encrypt(string $plaintext, string $context): string
{
$version = chr($this->current);
$nonce = random_bytes(self::NONCE);
$tag = '';
$ciphertext = openssl_encrypt(
$plaintext, self::CIPHER, $this->key($this->current),
OPENSSL_RAW_DATA, $nonce, $tag, $version.$context, self::TAG
);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed.');
}
return $version.$nonce.$ciphertext.$tag;
}
public function decrypt(string $blob, string $context): string
{
if (strlen($blob) < 1 + self::NONCE + self::TAG) {
throw new RuntimeException('Ciphertext too short.');
}
$version = ord($blob[0]);
$nonce = substr($blob, 1, self::NONCE);
$tag = substr($blob, -self::TAG);
$ciphertext = substr($blob, 1 + self::NONCE, -self::TAG);
$plaintext = openssl_decrypt(
$ciphertext, self::CIPHER, $this->key($version),
OPENSSL_RAW_DATA, $nonce, $tag, $blob[0].$context
);
if ($plaintext === false) {
throw new RuntimeException('Authentication failed: wrong key, context or tampered data.');
}
return $plaintext;
}
/** Re-encrypt under the current key; returns null when already current. */
public function rotate(string $blob, string $context): ?string
{
return ord($blob[0]) === $this->current
? null
: $this->encrypt($this->decrypt($blob, $context), $context);
}
private function key(int $version): string
{
return $this->keys[$version]
?? throw new RuntimeException("Unknown key version {$version}."); // fail closed
}
}Output of the Go program:
00000000 01 4c 63 cc 5a 2f 24 d6 5a 09 a3 0a df 6c 53 0f |.Lc.Z/$.Z....lS.|
00000010 22 d3 2a d0 49 62 d5 a9 e1 7b 11 a9 13 ed 42 36 |".*.Ib...{....B6|
00000020 00 18 08 1a 67 4e 15 a6 40 38 6e d7 |....gN..@8n.|
moved to another row: cipher: message authentication failed
rotated=true version=2 plaintext="ann@example.com"
old blob after retirement: unknown key version: 1Encrypt to a public key: X25519 + HKDF hybrid
// Package main shows hybrid public-key encryption: X25519 key agreement with an
// ephemeral sender key, HKDF-SHA256 to turn the shared secret into an AES key,
// and AES-256-GCM for the data. Output: ephemeral public key (32) | sealed data.
// This is the shape of ECIES, HPKE base mode (RFC 9180) and age's X25519 recipient.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"log"
)
const info = "academy-hybrid-v1" // domain separation: change it and keys change
func deriveKey(shared, ephPub, recipientPub []byte) ([]byte, error) {
// Bind both public keys into the derivation so the key is tied to this exchange.
ctx := info + string(ephPub) + string(recipientPub)
return hkdf.Key(sha256.New, shared, nil, ctx, 32)
}
func seal(key, plaintext, aad []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// The key is fresh for every message (new ephemeral key each time),
// so a fixed all-zero nonce is used exactly once per key.
nonce := make([]byte, gcm.NonceSize())
return gcm.Seal(nil, nonce, plaintext, aad), nil
}
func open(key, sealed, aad []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return gcm.Open(nil, make([]byte, gcm.NonceSize()), sealed, aad)
}
// Encrypt needs only the recipient's public key.
func Encrypt(recipient *ecdh.PublicKey, plaintext, aad []byte) ([]byte, error) {
eph, err := ecdh.X25519().GenerateKey(rand.Reader) // fresh ephemeral key per message
if err != nil {
return nil, err
}
shared, err := eph.ECDH(recipient)
if err != nil {
return nil, err
}
key, err := deriveKey(shared, eph.PublicKey().Bytes(), recipient.Bytes())
if err != nil {
return nil, err
}
sealed, err := seal(key, plaintext, aad)
if err != nil {
return nil, err
}
return append(eph.PublicKey().Bytes(), sealed...), nil
}
// Decrypt needs the recipient's private key.
func Decrypt(priv *ecdh.PrivateKey, msg, aad []byte) ([]byte, error) {
if len(msg) < 32+16 {
return nil, errors.New("message too short")
}
ephPub, err := ecdh.X25519().NewPublicKey(msg[:32])
if err != nil {
return nil, err
}
shared, err := priv.ECDH(ephPub) // fails on the all-zero shared secret
if err != nil {
return nil, err
}
key, err := deriveKey(shared, msg[:32], priv.PublicKey().Bytes())
if err != nil {
return nil, err
}
return open(key, msg[32:], aad)
}
func main() {
recipient, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
log.Fatal(err)
}
msg, err := Encrypt(recipient.PublicKey(), []byte("card=4111111111111111"), []byte("payments:v1"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("message: %d bytes = 32 ephemeral pub + %d ciphertext + 16 tag\n", len(msg), len(msg)-48)
pt, err := Decrypt(recipient, msg, []byte("payments:v1"))
fmt.Printf("decrypted: %q err=%v\n", pt, err)
msg[40] ^= 1
_, err = Decrypt(recipient, msg, []byte("payments:v1"))
fmt.Println("tampered:", err)
}<?php
namespace App\Support\Crypto;
use RuntimeException;
/**
* Hybrid encryption with libsodium X25519 + HKDF-SHA256 + AES-256-GCM, the same
* construction as the Go example (not a tested wire-compatible twin):
* ephemeral public key (32) | ciphertext | tag (16).
*/
final class HybridBox
{
private const INFO = 'academy-hybrid-v1';
/** @return array{public: string, secret: string} raw 32-byte keys */
public static function keyPair(): array
{
$pair = sodium_crypto_box_keypair();
return [
'public' => sodium_crypto_box_publickey($pair),
'secret' => sodium_crypto_box_secretkey($pair),
];
}
public static function encrypt(string $plaintext, string $recipientPublic, string $aad = ''): string
{
$eph = self::keyPair(); // fresh ephemeral key for every message
$shared = sodium_crypto_scalarmult($eph['secret'], $recipientPublic);
$key = self::derive($shared, $eph['public'], $recipientPublic);
// The key is single-use, so a fixed all-zero nonce is used once per key.
$tag = '';
$ct = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA,
str_repeat("\0", 12), $tag, $aad, 16);
sodium_memzero($shared);
return $eph['public'].$ct.$tag;
}
public static function decrypt(string $message, string $recipientSecret, string $aad = ''): string
{
$ephPublic = substr($message, 0, 32);
$tag = substr($message, -16);
$ct = substr($message, 32, -16);
$shared = sodium_crypto_scalarmult($recipientSecret, $ephPublic);
$recipientPublic = sodium_crypto_scalarmult_base($recipientSecret);
$key = self::derive($shared, $ephPublic, $recipientPublic);
$pt = openssl_decrypt($ct, 'aes-256-gcm', $key, OPENSSL_RAW_DATA,
str_repeat("\0", 12), $tag, $aad);
return $pt === false ? throw new RuntimeException('Cannot decrypt message.') : $pt;
}
private static function derive(string $shared, string $ephPublic, string $recipientPublic): string
{
// PHP order is (algo, key, length, info, salt); Go's hkdf.Key is (hash, secret, salt, info, length).
return hash_hkdf('sha256', $shared, 32, self::INFO.$ephPublic.$recipientPublic, '');
}
/** The library one-liner when you do not need interop with your own format. */
public static function sealed(string $plaintext, string $recipientPublic): string
{
return sodium_crypto_box_seal($plaintext, $recipientPublic);
}
}message: 69 bytes = 32 ephemeral pub + 21 ciphertext + 16 tag
decrypted: "card=4111111111111111" err=<nil>
tampered: cipher: message authentication failedFor production interop prefer a standard: HPKE (RFC 9180), age (filippo.io/age in Go, the age CLI from PHP), or libsodium crypto_box_seal on both sides (Go x/crypto/nacl/box.SealAnonymous).
Sign and verify with Ed25519
// Package main signs and verifies with Ed25519 (RFC 8032) and shows why a
// signature, unlike a MAC, can be checked by anyone holding the public key.
package main
import (
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"fmt"
"log"
)
func main() {
// Done once; the private key lives in a KMS/HSM or a secret store.
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
log.Fatal(err)
}
release := []byte(`{"artifact":"app-v1.4.2.tar.gz","sha256":"9f86d0..."}`)
sig := ed25519.Sign(priv, release) // deterministic: same key + message = same signature
fmt.Printf("public key %d bytes, signature %d bytes\n", len(pub), len(sig))
fmt.Println("sig:", base64.RawURLEncoding.EncodeToString(sig))
// Any verifier needs only pub; it cannot create signatures.
fmt.Println("valid:", ed25519.Verify(pub, release, sig))
release[13] = 'X'
fmt.Println("after tampering:", ed25519.Verify(pub, release, sig))
}<?php
namespace App\Support\Crypto;
/**
* Ed25519 detached signatures with libsodium (bundled with PHP since 7.2).
* Secret key: 64 bytes (seed + public key); public key: 32 bytes; signature: 64 bytes.
*/
final class Ed25519Signer
{
/** @return array{public: string, secret: string} */
public static function keyPair(): array
{
$pair = sodium_crypto_sign_keypair();
return [
'public' => sodium_crypto_sign_publickey($pair),
'secret' => sodium_crypto_sign_secretkey($pair),
];
}
public static function sign(string $message, string $secretKey): string
{
return sodium_crypto_sign_detached($message, $secretKey);
}
public static function verify(string $signature, string $message, string $publicKey): bool
{
return strlen($signature) === SODIUM_CRYPTO_SIGN_BYTES
&& sodium_crypto_sign_verify_detached($signature, $message, $publicKey);
}
}
// Usage: sign a release manifest in CI, verify it on every server with only the public key.
// $keys = Ed25519Signer::keyPair();
// $sig = Ed25519Signer::sign($manifestJson, $keys['secret']);
// Ed25519Signer::verify($sig, $manifestJson, $keys['public']); // truepublic key 32 bytes, signature 64 bytes
sig: oC_a8SjVFg126mvx2vQu3GlJRHQAOoi2uxO26xWZSUnMHnL2pIrvsfOiuDzCDwdM9IZzxM_nOIT-dOXOyf7xAg
valid: true
after tampering: falseSign bytes, not objects: serialise once (canonical JSON, Protobuf with deterministic options, or the raw file) and sign exactly what you send.
Verify a webhook with HMAC and a constant-time compare
// Package main signs and verifies a webhook with HMAC-SHA256 and a constant-time
// comparison. Header format: "t=<unix>,v1=<hex hmac of t + '.' + body>".
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"time"
)
const tolerance = 5 * time.Minute
func sign(secret, body []byte, ts int64) string {
mac := hmac.New(sha256.New, secret)
fmt.Fprintf(mac, "%d.", ts) // timestamp is inside the MAC: replay window is bounded
mac.Write(body)
return fmt.Sprintf("t=%d,v1=%s", ts, hex.EncodeToString(mac.Sum(nil)))
}
func verify(secret, body []byte, header string, now time.Time) error {
var ts int64
var got []byte
for _, part := range strings.Split(header, ",") {
k, v, _ := strings.Cut(part, "=")
switch k {
case "t":
ts, _ = strconv.ParseInt(v, 10, 64)
case "v1":
got, _ = hex.DecodeString(v)
}
}
if ts == 0 || len(got) != sha256.Size {
return errors.New("malformed signature header")
}
if d := now.Sub(time.Unix(ts, 0)); d > tolerance || d < -tolerance {
return errors.New("timestamp outside tolerance")
}
mac := hmac.New(sha256.New, secret)
fmt.Fprintf(mac, "%d.", ts)
mac.Write(body)
// WRONG: string(got) == string(want) or bytes.Equal: stop at the first
// different byte and leak, through timing, how many bytes matched.
if !hmac.Equal(got, mac.Sum(nil)) {
return errors.New("signature mismatch")
}
return nil
}
func main() {
secret := []byte("whsec_test_only_use_32_random_bytes")
body := []byte(`{"event":"invoice.paid","id":"in_123"}`)
now := time.Unix(1764000000, 0)
h := sign(secret, body, now.Unix())
fmt.Println(h)
fmt.Println("ok:", verify(secret, body, h, now))
fmt.Println("tampered:", verify(secret, []byte(`{"event":"invoice.paid","id":"in_999"}`), h, now))
fmt.Println("replayed later:", verify(secret, body, h, now.Add(time.Hour)))
}<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Verifies "X-Signature: t=<unix>,v1=<hex hmac-sha256 of t.body>" with a
* constant-time comparison and a replay window. Same format as the Go example.
*/
class VerifyWebhookSignature
{
private const TOLERANCE = 300; // seconds
public function handle(Request $request, Closure $next): Response
{
$secret = (string) config('services.billing.webhook_secret');
parse_str(str_replace(',', '&', (string) $request->header('X-Signature')), $parts);
$ts = (int) ($parts['t'] ?? 0);
$given = (string) ($parts['v1'] ?? '');
if ($ts === 0 || abs(time() - $ts) > self::TOLERANCE) {
abort(400, 'Stale or missing timestamp.');
}
$expected = hash_hmac('sha256', $ts.'.'.$request->getContent(), $secret);
// WRONG: $expected === $given or strcmp(): returns at the first different byte.
if (! hash_equals($expected, $given)) { // known string first, user string second
abort(401, 'Invalid signature.');
}
return $next($request);
}
/** What the sender does. */
public static function sign(string $body, string $secret, int $ts): string
{
return 't='.$ts.',v1='.hash_hmac('sha256', $ts.'.'.$body, $secret);
}
}t=1764000000,v1=083da225651d93f0e4002fd6f1cfbdd18d0b8091ce4ccd8c63b25da4c8dfdd62
ok: <nil>
tampered: signature mismatch
replayed later: timestamp outside toleranceVerify on the raw body bytes ($request->getContent(), not re-encoded JSON), and keep the timestamp inside the MAC so a captured request cannot be replayed after the tolerance.
Generate tokens, keys and IDs with a CSPRNG
// Package main generates secrets with crypto/rand and shows the math/rand mistake.
package main
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"math/big"
mrand "math/rand/v2"
)
func main() {
// 1. A ready-made secret string: base32, at least 128 bits (Go 1.24+).
fmt.Println("rand.Text(): ", rand.Text())
// 2. 32 random bytes as URL-safe base64: API keys, reset tokens, session IDs.
b := make([]byte, 32)
rand.Read(b) // never returns an error; crashes the program if the OS fails
fmt.Println("base64url(32B): ", base64.RawURLEncoding.EncodeToString(b))
// 3. A 256-bit symmetric key in hex (what `openssl rand -hex 32` prints).
fmt.Println("hex key: ", hex.EncodeToString(b))
// 4. A uniform 6-digit OTP without modulo bias.
n, _ := rand.Int(rand.Reader, big.NewInt(1_000_000))
fmt.Printf("otp: %06d\n", n.Int64())
// 5. UUIDv4 (RFC 9562): 122 random bits, version and variant fixed.
u := make([]byte, 16)
rand.Read(u)
u[6] = (u[6] & 0x0f) | 0x40
u[8] = (u[8] & 0x3f) | 0x80
fmt.Printf("uuid v4: %x-%x-%x-%x-%x\n", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
// WRONG for secrets: math/rand is fast and statistically fine but predictable.
// With a fixed seed every run prints the same "token".
r := mrand.New(mrand.NewPCG(42, 42))
fmt.Printf("math/rand seeded: %016x (same every run)\n", r.Uint64())
}<?php
namespace App\Support\Crypto;
use Illuminate\Support\Str;
final class Tokens
{
/** 32 random bytes, URL-safe base64 without padding: reset links, API keys. */
public static function urlToken(): string
{
return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
}
/** A 256-bit key as hex, like `openssl rand -hex 32`. */
public static function hexKey(): string
{
return bin2hex(random_bytes(32));
}
/** A uniform 6-digit code; random_int() is a CSPRNG without modulo bias. */
public static function otp(): string
{
return str_pad((string) random_int(0, 999_999), 6, '0', STR_PAD_LEFT);
}
/** Laravel helpers: Str::random() is built on random_bytes(); Str::uuid() is a v4 UUID. */
public static function laravelHelpers(): array
{
return [
'random' => Str::random(40),
'uuid' => (string) Str::uuid(),
];
}
// WRONG for secrets: mt_rand(), rand(), uniqid(), md5(microtime()), str_shuffle().
// They are predictable; mt_srand(42) makes mt_rand() repeat the same sequence.
}rand.Text(): SN45T7JRDWPMZ2MNCT7M2UUOBX
base64url(32B): OAOIA7tFoRwv2XYopw_nSi5P62ZYV0NDheBuvQnOs0o
hex key: 38038803bb45a11c2fd97628a70fe74a2e4feb665857434385e06ebd09ceb34a
otp: 886081
uuid v4: 1d493de8-0197-4bb6-a749-1ca4d5216f0a
math/rand seeded: 9e89c2ade4a6b4c2 (same every run)Hard-to-misuse defaults: secretbox, XChaCha20 and Laravel Crypt
// Package main shows the hard-to-misuse x/crypto options: NaCl secretbox
// (XSalsa20-Poly1305) and XChaCha20-Poly1305, both with 24-byte random nonces.
package main
import (
"crypto/rand"
"fmt"
"log"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/nacl/secretbox"
)
func main() {
var key [32]byte
rand.Read(key[:])
// NaCl secretbox: nonce is prepended by convention.
var nonce [24]byte
rand.Read(nonce[:])
box := secretbox.Seal(nonce[:], []byte("hello"), &nonce, &key)
var n [24]byte
copy(n[:], box[:24])
pt, ok := secretbox.Open(nil, box[24:], &n, &key)
fmt.Printf("secretbox: %d bytes, ok=%v, %q\n", len(box), ok, pt)
// XChaCha20-Poly1305: an AEAD with AAD and a 192-bit nonce that is safe to pick at random.
aead, err := chacha20poly1305.NewX(key[:])
if err != nil {
log.Fatal(err)
}
xn := make([]byte, aead.NonceSize(), aead.NonceSize()+5+aead.Overhead())
rand.Read(xn)
ct := aead.Seal(xn, xn, []byte("hello"), []byte("ctx"))
pt, err = aead.Open(nil, ct[:aead.NonceSize()], ct[aead.NonceSize():], []byte("ctx"))
fmt.Printf("xchacha: %d bytes, err=%v, %q\n", len(ct), err, pt)
}<?php
namespace App\Services;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
/**
* Laravel's built-in encrypter (Illuminate\Encryption\Encrypter, 13.x):
* - config/app.php 'cipher' => 'AES-256-CBC' (default); also accepts AES-128-CBC,
* AES-128-GCM and AES-256-GCM.
* - CBC: random 16-byte IV, HMAC-SHA256 over base64(iv).base64(value) with the same APP_KEY,
* checked with hash_equals() before decrypting (encrypt-then-MAC).
* - GCM: random 12-byte IV, 16-byte tag, empty "mac" field, no AAD.
* - Payload: base64(JSON {"iv","value","mac","tag"}); no key id: decryption tries
* APP_KEY then every key in APP_PREVIOUS_KEYS.
*/
final class CryptUsage
{
public function roundTrip(string $secret): string
{
$payload = Crypt::encryptString($secret); // no serialize()
try {
return Crypt::decryptString($payload);
} catch (DecryptException $e) {
// "The MAC is invalid." (CBC) or "Could not decrypt the data." (GCM / wrong key)
report($e);
throw $e;
}
}
/** Inspect a payload: shows the fields, never the key. */
public function inspect(string $payload): array
{
$json = json_decode(base64_decode($payload), true);
return [
'iv_bytes' => strlen(base64_decode($json['iv'])),
'has_mac' => $json['mac'] !== '',
'has_tag' => ($json['tag'] ?? '') !== '',
];
}
}secretbox: 45 bytes, ok=true, "hello"
xchacha: 45 bytes, err=<nil>, "hello"Both outputs are 24-byte nonce + 5 bytes + 16-byte tag = 45 bytes.
Common mistakes
| Mistake | What breaks | Seen as | Fix |
|---|---|---|---|
| ECB mode | Equal blocks leak, blocks can be cut and pasted | aes-*-ecb in PHP/OpenSSL code | AEAD |
| IV / nonce reuse (GCM, CTR, ChaCha20) | XOR of plaintexts; GCM tag forgery | Constant nonce, counter reset on restart, timestamp nonce | Random nonce + rotation budget, persisted counter, XChaCha20 |
| Unauthenticated CBC / CTR | Bit flipping, padding oracle | openssl_encrypt('aes-256-cbc') with no MAC | AEAD or encrypt-then-MAC |
| MAC-then-encrypt | Receiver decrypts before checking | Custom "encrypt(json + hmac)" formats | Encrypt-then-MAC or AEAD |
| Truncated MAC | Fewer bits to guess | Comparing first 8 hex chars of a tag | Full 32-byte HMAC-SHA256 (≥ 128 bits) |
== comparison of MACs/tokens | Timing attack | if ($sig === $expected) | hash_equals, hmac.Equal |
| RSA PKCS#1 v1.5 encryption | Bleichenbacher padding oracle | OPENSSL_PKCS1_PADDING, rsa.EncryptPKCS1v15 | OAEP, or better a KEM (X25519/HPKE) |
| Raw ECDH output as key | Biased, context-free key | key := shared | HKDF with info |
| Same key for two purposes | Cross-protocol attacks, rotation coupling | One APP_KEY for encryption, MAC and signed URLs | Separate keys or HKDF domain separation |
| ECDSA with bad randomness | Private key recovery | Custom k, broken RNG on embedded devices | Ed25519 or RFC 6979 / hedged ECDSA |
| Home-made protocols | Unknown | "We XOR with a rotating key", custom handshake | TLS, HPKE, age, PASETO |
| Hard-coded keys | Everyone with repo access, CI logs, Docker layers has the key | const key = "...", .env committed | KMS / secret manager, rotation |
| Logging plaintext or keys | Secret in log pipeline forever | Log::debug($request->all()), panics printing structs | Redaction, #[\SensitiveParameter], typed secrets |
math/rand / mt_rand for tokens | Predictable tokens | Reset links, invite codes, OTPs | crypto/rand, random_bytes, random_int |
| Hash as password storage | Fast brute force | sha256($password) | Argon2id/bcrypt (page) |
| No key ID in ciphertext | Rotation by trial and error | Laravel-style payloads at scale | Version byte or key ID in AAD |
Troubleshooting
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
| Every decryption fails after deploy | New APP_KEY / key not loaded | Compare key fingerprint (HMAC of a constant) across hosts | Put old key in APP_PREVIOUS_KEYS / key ring |
| Decryption fails only for some rows | Value copied between rows or contexts (AAD mismatch) | Log context used at encrypt vs decrypt | Re-encrypt with the right context |
invalid key size | Hex or base64 string passed as raw key | len(key) is 44/64 instead of 32 | Decode first; Laravel needs the base64: prefix |
| Go encrypts, PHP cannot decrypt | Different layout (nonce position, tag appended vs separate), different HKDF argument order | Hex-dump both sides | Document the format; tag is the last 16 bytes in Go, separate $tag in PHP |
Decrypted text has trailing \x0e\x0e… | Padding not removed (CBC with -nopad / raw mode) | Look at last byte value | Use the library unpadding, or AEAD |
| Signature valid locally, invalid at consumer | Bytes differ (JSON re-serialisation, newline, encoding) | Hash the exact bytes on both sides | Sign and verify the raw transmitted bytes |
| Webhooks fail intermittently | Clock skew or body modified by middleware | Compare server time; log raw body length | NTP; read raw body before parsing |
| Same "random" tokens across pods | PRNG seeded with a constant or time at start | Grep for math/rand, mt_srand | CSPRNG |
| Duplicate GCM nonces in audit | Counter in memory, multiple writers | Count nonces per key in logs | Random nonces with budget, or per-writer prefix |
sodium_crypto_aead_aes256gcm_* throws on some servers | CPU without AES-NI / ARM build | sodium_crypto_aead_aes256gcm_is_available() | XChaCha20-Poly1305 or openssl GCM |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Encrypting fields in one app | AES-256-GCM (Go) / Laravel Crypt with GCM or CBC+MAC | Version byte + AAD with record context | Fast, hardware accelerated, rotation-ready |
| Many writers, high volume, no coordination | XChaCha20-Poly1305 | Random 24-byte nonces | No nonce budget to track |
| No AES hardware (old ARM, IoT) | ChaCha20-Poly1305 | n/a | About 3x faster in software (RFC 8439) |
| Encrypt to a recipient's public key | HPKE / age / crypto_box_seal | Sign too if sender identity matters | Standard formats, reviewed |
| Signatures, greenfield | Ed25519 | Canonical bytes | Deterministic, fast, small |
| Signatures under FIPS / X.509 / cloud KMS | ECDSA P-256 or RSA-PSS 3072 | RFC 6979 or hedged k | Approved algorithms |
| Two-party message authentication | HMAC-SHA256 | Timestamp + constant-time compare | Simple, no PKI |
| Derive several keys from one secret | HKDF-SHA256 | One info label per purpose | Domain separation |
| Passwords | Argon2id / bcrypt | Per-user salt (built in) | Slow by design |
| Long-lived secrets vs future quantum attackers | Hybrid X25519 + ML-KEM-768 | AES-256 data keys | "Harvest now, decrypt later" protection |
| Compliance needs key custody | Envelope encryption with KMS/HSM | Key IDs, audit logs | KEK never leaves the HSM |
In architecture: from a single process to a distributed system
Primitives do not change with scale; key management does. The questions grow from "which mode?" to "who holds which key, how is it rotated, and what happens when one service is compromised?".
Monolith: one process, one key ring
How it shows up: a Laravel or Go monolith encrypts a few columns (national IDs, OAuth refresh tokens), verifies incoming webhooks, signs password-reset links and generates tokens.
Everyday example: a shop stores customers' phone numbers with the encrypted cast, verifies Stripe-style webhooks with HMAC, and generates reset tokens with Str::random(64). The only key is APP_KEY plus a webhook secret per provider, both in the secret store, not in Git.
Production example: the same shop at 50 million rows uses the versioned key ring for PII columns with AAD "customers.phone:<id>", a separate HKDF-derived key for the blind index, and a nightly job that re-encrypts rows still on old versions; the rotation progress query is on the dashboard.
Modular monolith: one key per module and purpose
Modules (Billing, Identity, Support) should not share keys: a bug in Support's export must not be able to decrypt Billing's card tokens. Derive per-module keys with HKDF (info = "billing:v1:pan") or keep separate keys in the secret store, and put the module name in the AAD. Signed URLs, cookies and field encryption get different keys even when they come from one master, so a leak of one does not unlock the others.
Microservices: signatures across boundaries, encryption per owner
What changes: many verifiers. A token or event that must be trusted by ten services should be signed (Ed25519/ES256), not HMACed with a secret copied into ten deployments. Services fetch the public key set (JWKS) and cannot forge.
Identity service API gateway Orders service Billing service
1 sign JWT (EdDSA, kid=k7)
2 ---- token ----> verify with JWKS k7
3 ---- request + token ----> verify with JWKS k7
4 publish OrderPlaced (signed envelope, kid=k7)
5 verify signature; decrypt PAN with
its OWN key (only Billing holds it)Payload fields only one service may read (card data, health data) are encrypted to that service's key (hybrid) so intermediaries, brokers and logs see ciphertext. Transport between services is mTLS (mTLS for services); message-level signing and encryption are what survive when a message is stored in a queue or a log.
Distributed data: replicas, caches, backups and regions
Replicas and backups carry ciphertext and key versions with them: a backup restored after a key was retired cannot be read, so retirement must respect the backup retention window. Caches must not hold decrypted values longer than the data's policy allows; cache the ciphertext or nothing. Multi-region setups replicate KMS keys (multi-region keys) or wrap DEKs per region; nonce uniqueness must hold across regions, which is another reason to prefer random nonces (with a budget) or XChaCha20 over counters. Crypto-shredding: deleting a per-tenant or per-user DEK makes every replica and backup copy unreadable, which is how immutable logs meet erasure requirements (details in database encryption).
Scaling path: 1×, 10×, 100×
| Load | What changes | Crypto consequence |
|---|---|---|
| 1× (one app, one DB) | APP_KEY + a few secrets | Laravel Crypt or one Go key ring; HMAC webhooks; CSPRNG tokens |
| 10× (several services, queues) | Many verifiers, more writers | Signatures with JWKS and key IDs; versioned ciphertexts; nonce budget per key (GCM 2^32) or XChaCha20; keys per service |
| 100× (multi-region, tenants, compliance) | KMS/HSM, per-tenant keys, audits | Envelope encryption with DEK caching, per-tenant DEKs for crypto-shredding, automated rotation, hybrid post-quantum key exchange for long-lived data |
Lab
Everything below was run on macOS (Apple M5, arm64) with Go 1.27.4 and LibreSSL 3.3.6; the Go module declares go 1.24.0. Docker and PHP were not available on the machine, so PHP snippets are reviewed, not executed. Clone the snippets and run from docs/snippets/foundations/cryptography-fundamentals/go.
1. The ECB penguin on a bitmap
// Package main reproduces the "ECB penguin" on a tiny bitmap: every pixel is one
// 16-byte AES block. ECB maps equal blocks to equal ciphertexts, so the picture
// survives encryption; CTR (and GCM, which is CTR inside) does not.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"strings"
)
var picture = []string{
"................................",
"...........##########...........",
".........##############.........",
"........####..####..####........",
"........####..####..####........",
"........################........",
"........######....######........",
".........####......####.........",
"..........##############........",
"...........############.........",
"............##########..........",
"................................",
}
func pixels() []byte {
var buf []byte
for _, row := range picture {
for _, c := range row {
fill := byte(0x00) // white pixel = 16 zero bytes
if c == '#' {
fill = 0xff // black pixel = 16 0xff bytes
}
buf = append(buf, make16(fill)...)
}
}
return buf
}
func make16(b byte) []byte {
p := make([]byte, 16)
for i := range p {
p[i] = b
}
return p
}
// render prints one character per 16-byte block, chosen by the block's first
// byte, and counts distinct blocks: equal blocks always print the same character.
func render(title string, data []byte) {
const symbols = ".abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+#"
seen := map[string]bool{}
var sb strings.Builder
w := len(picture[0])
for i := 0; i < len(data); i += 16 {
seen[string(data[i:i+16])] = true
sb.WriteByte(symbols[int(data[i])%len(symbols)])
if (i/16+1)%w == 0 {
sb.WriteByte('\n')
}
}
fmt.Printf("%s (%d distinct blocks of %d)\n%s\n", title, len(seen), len(data)/16, sb.String())
}
func main() {
key := make([]byte, 32)
rand.Read(key)
block, _ := aes.NewCipher(key)
pt := pixels()
// ECB: Go deliberately has no ECB mode; this loop IS ECB.
ecb := make([]byte, len(pt))
for i := 0; i < len(pt); i += 16 {
block.Encrypt(ecb[i:i+16], pt[i:i+16])
}
ctr := make([]byte, len(pt))
iv := make([]byte, 16)
rand.Read(iv)
cipher.NewCTR(block, iv).XORKeyStream(ctr, pt)
render("plaintext", pt)
render("AES-256-ECB", ecb)
render("AES-256-CTR", ctr)
}$ go run ./lab/ecb
plaintext (2 distinct blocks of 384)
................................
...........7777777777...........
.........77777777777777.........
........7777..7777..7777........
... (8 more rows, same shape)
AES-256-ECB (2 distinct blocks of 384)
00000000000000000000000000000000
00000000000666666666600000000000
00000000066666666666666000000000
00000000666600666600666600000000
00000000666600666600666600000000
00000000666666666666666600000000
00000000666666000066666600000000
00000000066660000006666000000000
00000000006666666666666600000000
... (3 more rows)
AES-256-CTR (384 distinct blocks of 384)
Em39.He3#F0h.OQeYGRLgI8BMimsihew
9ywaFYAufMi+mKxIz5RA6jeEdAb8DToE
3wlLRjhTvM3aDy3iLTxMRjBcI63c7JK#
... (9 more rows of noise)The face survives ECB untouched (different characters, same shape); CTR, the core of GCM, turns it into noise.
2. Nonce reuse recovers a plaintext
// Package main shows what one repeated AES-GCM nonce costs: the XOR of the two
// ciphertexts equals the XOR of the two plaintexts, so knowing one message
// reveals the other without the key.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
)
func xor(a, b []byte) []byte {
out := make([]byte, min(len(a), len(b)))
for i := range out {
out[i] = a[i] ^ b[i]
}
return out
}
func main() {
key := make([]byte, 32)
rand.Read(key)
block, _ := aes.NewCipher(key)
gcm, _ := cipher.NewGCM(block)
nonce := make([]byte, 12) // BUG: a constant nonce, e.g. from a config file
p1 := []byte(`{"to":"alice","amount":100}`)
p2 := []byte(`{"to":"carol","amount":900}`)
c1 := gcm.Seal(nil, nonce, p1, nil)
c2 := gcm.Seal(nil, nonce, p2, nil)
body1, body2 := c1[:len(p1)], c2[:len(p2)] // drop the 16-byte tags
fmt.Printf("c1 xor c2 = %x\n", xor(body1, body2))
fmt.Printf("p1 xor p2 = %x\n", xor(p1, p2))
// The attacker knows (or guesses) p1, e.g. a fixed JSON template.
recovered := xor(xor(body1, body2), p1)
fmt.Printf("recovered p2 = %s\n", recovered)
}$ go run ./lab/noncereuse
c1 xor c2 = 00000000000000020d1b0c09000000000000000000000008000000
p1 xor p2 = 00000000000000020d1b0c09000000000000000000000008000000
recovered p2 = {"to":"carol","amount":900}The zero bytes show where the two messages agree; the non-zero bytes are exactly the differences (alice/carol, 1/9). No key was used to recover p2.
3. Padding-oracle sketch
// Package main is a padding-oracle sketch against AES-CBC with PKCS#7 padding
// and no MAC. The attacker never sees the key; it only learns, per request,
// whether the padding was valid (a different error, status code or timing).
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
)
var key = func() []byte { k := make([]byte, 16); rand.Read(k); return k }()
func encrypt(pt []byte) []byte {
n := 16 - len(pt)%16
pt = append(pt, bytes.Repeat([]byte{byte(n)}, n)...)
out := make([]byte, 16+len(pt))
rand.Read(out[:16]) // IV
block, _ := aes.NewCipher(key)
cipher.NewCBCEncrypter(block, out[:16]).CryptBlocks(out[16:], pt)
return out
}
var queries int
// oracle is the server: decrypt, check padding, report only "valid padding or not".
func oracle(ivct []byte) bool {
queries++
block, _ := aes.NewCipher(key)
pt := make([]byte, len(ivct)-16)
cipher.NewCBCDecrypter(block, ivct[:16]).CryptBlocks(pt, ivct[16:])
n := int(pt[len(pt)-1])
if n == 0 || n > 16 {
return false
}
for _, b := range pt[len(pt)-n:] {
if int(b) != n {
return false
}
}
return true
}
// attackBlock recovers one plaintext block from (previous block, target block).
func attackBlock(prev, target []byte) []byte {
inter := make([]byte, 16) // D_k(target), recovered byte by byte from the end
for pos := 15; pos >= 0; pos-- {
pad := byte(16 - pos)
forged := make([]byte, 16)
for j := pos + 1; j < 16; j++ {
forged[j] = inter[j] ^ pad
}
for g := 0; g < 256; g++ {
forged[pos] = byte(g)
if !oracle(append(append([]byte{}, forged...), target...)) {
continue
}
if pos == 15 { // rule out an accidental 0x02 0x02 ending
forged[14] ^= 1
ok := oracle(append(append([]byte{}, forged...), target...))
forged[14] ^= 1
if !ok {
continue
}
}
inter[pos] = byte(g) ^ pad
break
}
}
out := make([]byte, 16)
for i := range out {
out[i] = inter[i] ^ prev[i]
}
return out
}
func main() {
ct := encrypt([]byte("session=admin;uid=42;exp=1764000000"))
var recovered []byte
for i := 16; i < len(ct); i += 16 {
recovered = append(recovered, attackBlock(ct[i-16:i], ct[i:i+16])...)
}
fmt.Printf("recovered: %q\n", recovered)
fmt.Printf("oracle queries: %d for %d blocks\n", queries, len(ct)/16-1)
}$ go run ./lab/paddingoracle
recovered: "session=admin;uid=42;exp=1764000000\r\r\r\r\r\r\r\r\r\r\r\r\r"
oracle queries: 5912 for 3 blocksAbout 2,000 requests per 16-byte block, never touching the key; the trailing \r bytes are the PKCS#7 padding (13 × 0x0d). The query count varies per run (6,453 in another run). Add a MAC checked before decryption and every forged request fails identically.
4. RSA vs ECC vs AES speed
// Package main measures symmetric vs asymmetric operations with testing.Benchmark.
package main
import (
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/mlkem"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
"testing"
"golang.org/x/crypto/chacha20poly1305"
)
func row(name string, f func(b *testing.B)) {
r := testing.Benchmark(f)
fmt.Printf("%-34s %12d ns/op\n", name, r.NsPerOp())
}
func main() {
msg := make([]byte, 1024)
digest := sha256.Sum256(msg)
key := make([]byte, 32)
rand.Read(key)
blk, _ := aes.NewCipher(key)
gcm, _ := cipher.NewGCM(blk)
chacha, _ := chacha20poly1305.New(key)
nonce := make([]byte, 12)
rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048)
ecKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
edPub, edPriv, _ := ed25519.GenerateKey(rand.Reader)
xA, _ := ecdh.X25519().GenerateKey(rand.Reader)
xB, _ := ecdh.X25519().GenerateKey(rand.Reader)
dk, _ := mlkem.GenerateKey768()
ek := dk.EncapsulationKey()
rsaSig, _ := rsa.SignPSS(rand.Reader, rsaKey, crypto.SHA256, digest[:], nil)
ecSig, _ := ecdsa.SignASN1(rand.Reader, ecKey, digest[:])
edSig := ed25519.Sign(edPriv, msg)
oaep, _ := rsa.EncryptOAEP(sha256.New(), rand.Reader, &rsaKey.PublicKey, key, nil)
row("AES-256-GCM seal 1 KiB", func(b *testing.B) {
for i := 0; i < b.N; i++ {
gcm.Seal(nil, nonce, msg, nil)
}
})
row("ChaCha20-Poly1305 seal 1 KiB", func(b *testing.B) {
for i := 0; i < b.N; i++ {
chacha.Seal(nil, nonce, msg, nil)
}
})
row("Ed25519 sign", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ed25519.Sign(edPriv, msg)
}
})
row("Ed25519 verify", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ed25519.Verify(edPub, msg, edSig)
}
})
row("ECDSA P-256 sign", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ecdsa.SignASN1(rand.Reader, ecKey, digest[:])
}
})
row("ECDSA P-256 verify", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ecdsa.VerifyASN1(&ecKey.PublicKey, digest[:], ecSig)
}
})
row("X25519 ECDH", func(b *testing.B) {
for i := 0; i < b.N; i++ {
xA.ECDH(xB.PublicKey())
}
})
row("ML-KEM-768 encapsulate", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ek.Encapsulate()
}
})
row("RSA-2048 PSS sign", func(b *testing.B) {
for i := 0; i < b.N; i++ {
rsa.SignPSS(rand.Reader, rsaKey, crypto.SHA256, digest[:], nil)
}
})
row("RSA-2048 PSS verify", func(b *testing.B) {
for i := 0; i < b.N; i++ {
rsa.VerifyPSS(&rsaKey.PublicKey, crypto.SHA256, digest[:], rsaSig, nil)
}
})
row("RSA-2048 OAEP decrypt", func(b *testing.B) {
for i := 0; i < b.N; i++ {
rsa.DecryptOAEP(sha256.New(), nil, rsaKey, oaep, nil)
}
})
row("RSA-2048 key generation", func(b *testing.B) {
for i := 0; i < b.N; i++ {
rsa.GenerateKey(rand.Reader, 2048)
}
})
}$ go run ./lab/speed
AES-256-GCM seal 1 KiB 220 ns/op
ChaCha20-Poly1305 seal 1 KiB 962 ns/op
Ed25519 sign 12324 ns/op
Ed25519 verify 24619 ns/op
ECDSA P-256 sign 14271 ns/op
ECDSA P-256 verify 33331 ns/op
X25519 ECDH 20842 ns/op
ML-KEM-768 encapsulate 21186 ns/op
RSA-2048 PSS sign 637831 ns/op
RSA-2048 PSS verify 19647 ns/op
RSA-2048 OAEP decrypt 616458 ns/op
RSA-2048 key generation 37023499 ns/opRead it as ratios, not absolutes: AES-GCM with hardware AES is about 4x faster than ChaCha20-Poly1305 here (on a CPU without AES instructions the order flips); an RSA-2048 private-key operation (sign or OAEP decrypt) costs about 50 Ed25519 signatures; RSA key generation takes 30–50 ms and varies run to run (it searches for primes); ML-KEM-768 encapsulation costs about the same as an X25519 exchange.
5. Bytes from the command line
openssl rand -hex 32 # a 256-bit key
head -c 16 /dev/urandom | xxd # raw CSPRNG bytes
printf "%s" "hello" | openssl dgst -sha256 -hmac "secret"
printf "YELLOW SUBMARINEYELLOW SUBMARINE" | openssl enc -aes-128-ecb -nopad -K 000102030405060708090a0b0c0d0e0f | xxdd597d45685028e37ea6c6e6209cf16811134685a1adb5fcd8b68465303b51bf7
00000000: a580 2e3b f631 d092 14ca 3cd9 7584 3d5c ...;.1....<.u.=\
88aab3ede8d3adf94d26ab90d3bafd4a2083070c3bcce9c014ee04a443847c0b
00000000: 761a b98c 7086 c509 261f 322c b3ff a7d9 v...p...&.2,....
00000010: 761a b98c 7086 c509 261f 322c b3ff a7d9 v...p...&.2,....6. Break your own code on purpose
- In
aeadkeys, change the context inDecryptand watchcipher: message authentication failed. - In
hmacsig, replacehmac.Equalwithstring(got) == string(mac.Sum(nil)): tests still pass, which is exactly why reviewers must look for it. - In
hybrid, droprecipientPubfrom the HKDF info: it still works, but the ciphertext is no longer bound to the recipient key; write down why that matters for re-targeting.
Common misconceptions
| Belief | Reality |
|---|---|
| Encryption gives integrity | Only AEAD, encrypt-then-MAC or signatures do; CTR/CBC alone can be modified |
| A secret algorithm adds security | Kerckhoffs: assume the design is known; secrecy belongs to the key |
| AES-256 means 256-bit security for my system | The weakest link is the mode, the nonce, the key storage or the comparison |
| Random GCM nonces are safe forever | 2^32 messages per key, then rotate, or use XChaCha20 |
| HMAC is a signature | Every verifier can forge; no non-repudiation |
| RSA can encrypt files | Only small payloads; use hybrid encryption |
| The ECDH shared secret is a key | Run it through HKDF with context |
| HKDF makes passwords strong | It cannot add entropy; use Argon2id/bcrypt |
/dev/random is better than /dev/urandom | Legacy; /dev/urandom/getrandom(2) is the right source |
| UUIDv4 is a secret | RFC 9562: must not be used as a security capability |
| Base64 or hex is encryption | It is encoding; anyone decodes it |
| Rotating a key re-encrypts the data | Only new data; old ciphertexts need a re-encryption job and a key ID |
| Timing attacks are theoretical over a network | RFC 8439 makes constant-time tag comparison a MUST |
Cheat sheet
| Topic | Remember |
|---|---|
| Default symmetric | AES-256-GCM or XChaCha20-Poly1305 through a library |
| GCM nonce | 12 bytes, unique per key; random OK up to 2^32 messages |
| XChaCha20 nonce | 24 bytes, random is fine |
| AAD | Bind context: record ID, column, key version, tenant |
| Never | ECB, unauthenticated CBC/CTR, MAC-then-encrypt, PKCS#1 v1.5 encryption |
| Signatures | Ed25519; ECDSA P-256 with RFC 6979; RSA-PSS for compatibility |
| Key exchange | X25519 → HKDF; ephemeral both sides for forward secrecy |
| Public-key encryption | Hybrid: HPKE, age, crypto_box_seal |
| MAC vs signature | MAC = shared key, verifiers can forge; signature = anyone verifies, only signer signs |
| KDF | HKDF with distinct info per purpose; Argon2id/bcrypt for passwords |
| Random | crypto/rand, random_bytes; never math/rand, mt_rand |
| Compare | hmac.Equal, hash_equals |
| Rotation | Key ID in ciphertext, re-encrypt job, retire after backups age out |
| Security levels | AES-128 ≈ RSA-3072 ≈ P-256; RSA-2048 = 112 bits |
| Post-quantum | ML-KEM (FIPS 203), ML-DSA (FIPS 204); hybrid X25519MLKEM768 now |
Laravel Crypt | AES-256-CBC + HMAC-SHA256 by default, GCM optional, no AAD, no key ID |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Which of confidentiality, integrity, authenticity and non-repudiation does HMAC-SHA256 give, and which does it not? Must-know
Answer
Answer: Integrity and authenticity among holders of the shared key. Not confidentiality (the message is in clear) and not non-repudiation (every verifier could have made the tag). See Security goals and MACs vs signatures.
2 — Why does an ECB-encrypted bitmap still show the picture? Must-know
Answer
Answer: ECB encrypts each block independently with the same key, so equal plaintext blocks give equal ciphertext blocks (SP 800-38A). Large areas of one colour stay one ciphertext value. See ECB and the lab.
3 — Two messages were encrypted with AES-GCM under the same key and the same nonce. What can an attacker do? Must-know
Answer
Answer: XOR the ciphertexts to get the XOR of the plaintexts (and recover one from the other if one is known), and recover the GHASH key to forge tags for that key. See GCM and the nonce-reuse lab.
4 — A service uses random 96-bit nonces with one AES-GCM key and encrypts 50,000 messages per second. What should you plan? Important
Answer
Answer: 2^32 messages per key is reached in about 24 hours (4.29 billion / 50,000 ≈ 86,000 s). Rotate keys well before that (versioned ciphertexts), or switch to XChaCha20-Poly1305. See GCM and rotation.
5 — Why is AES-CBC without a MAC dangerous even with a random IV? Must-know
Answer
Answer: An active attacker can modify ciphertexts and use any difference in the server's reaction to bad padding as an oracle to decrypt the data block by block. See CBC and the padding-oracle lab.
6 — What goes into AAD for an encrypted database column, and what does it protect against? Important
Answer
Answer: The key version and a context such as "users.email:42". It stops an attacker or a bug from moving a valid ciphertext into another row or relabelling it with another key. See AEAD and the code.
7 — Why should the X25519 shared secret go through HKDF, and what belongs in info? Important
Answer
Answer: The raw output is a structured group element, not a uniform key, and it carries no context. HKDF extracts a uniform key and info binds it to the protocol, version and public keys, giving domain separation. See Key exchange and KDFs.
8 — Ten microservices must verify tokens from one identity service. HMAC or signatures? Must-know
Answer
Answer: Signatures (Ed25519/ES256 with a JWKS). With HMAC every service holds the signing key and any one compromise lets the attacker mint tokens for all. See In architecture: microservices.
9 — What does ECDSA nonce reuse reveal, and how does Ed25519 avoid it? Good to know
Answer
Answer: Two signatures with the same k reveal k and then the private key. Ed25519 derives its nonce deterministically from the key and message (RFC 8032), so no per-signature randomness is needed. See Asymmetric cryptography.
10 — Your Laravel app sets a new APP_KEY. What happens to sessions and encrypted columns, and how do you avoid an outage? Important
Answer
Answer: Without the old key nothing old decrypts and users are logged out. Put the old key in APP_PREVIOUS_KEYS: Laravel encrypts with the current key and tries previous keys on decrypt. Re-encrypt columns, then remove the old key after backups age out. See Laravel Crypt.
11 — Why is $sig === $expected a vulnerability in a webhook handler? Must-know
Answer
Answer: It returns at the first differing byte, so response time leaks how many leading bytes matched, letting an attacker guess a valid tag byte by byte. Use hash_equals. See Constant-time comparison.
Glossary
| Term | Meaning |
|---|---|
| Confidentiality | Only authorised key holders can read the data |
| Integrity | Unauthorised changes are detected |
| Authenticity | The data provably came from a holder of a specific key |
| Non-repudiation | A third party can verify who signed; needs a digital signature |
| Kerckhoffs's principle | A system must stay secure when everything except the key is public |
| Don't roll your own | Use reviewed primitives, constructions and protocols through vetted libraries |
| Block cipher | Keyed permutation of fixed-size blocks; AES uses 128-bit blocks |
| Stream cipher | Generates a keystream XORed with data; ChaCha20, AES-CTR |
| AES-128 / AES-256 | AES with 128- or 256-bit keys (10 or 14 rounds), FIPS 197 |
| ECB | Electronic Codebook: each block encrypted independently; leaks patterns (the penguin) |
| CBC | Cipher Block Chaining: each block XORed with the previous ciphertext; needs padding and a random IV |
| PKCS#7 padding | n bytes of value n to fill the last block |
| Padding oracle | Any signal revealing whether padding was valid; decrypts CBC without the key (Vaudenay 2002) |
| CTR | Counter mode: encrypt a counter, XOR with data |
| GCM | Galois/Counter Mode: CTR + GHASH tag; NIST SP 800-38D |
| GHASH | Polynomial hash over GF(2^128) keyed by H = AES(k, 0) |
| Poly1305 | One-time polynomial MAC modulo 2^130 − 5, keyed from ChaCha20 in the AEAD |
| ChaCha20-Poly1305 | RFC 8439 AEAD: 32-byte key, 12-byte nonce, 16-byte tag |
| XChaCha20 | ChaCha20 with a 24-byte nonce via HChaCha20; safe with random nonces |
| AEAD | Authenticated Encryption with Associated Data: one call for confidentiality and integrity |
| AAD | Associated data: authenticated, not encrypted (headers, IDs, key version) |
| Tag | The MAC output of an AEAD, usually 16 bytes |
| Encrypt-then-MAC | MAC computed over the ciphertext with a separate key; checked before decrypting |
| MAC-then-encrypt | MAC over plaintext, then encrypted; source of padding-oracle bugs |
| Nonce | Number used once per key; public |
| IV | Initialisation vector; public per-message input to a mode |
| Salt | Public random input to a KDF or password hash |
| 2^32 limit | Max messages per AES-GCM key with random 96-bit nonces (NIST, Go docs) |
| Security level | log2 of the cost of the best known attack (112, 128, 192, 256 bits) |
| ML-KEM | Module-lattice KEM, FIPS 203 (August 2024), post-quantum |
| ML-DSA | Module-lattice signature, FIPS 204 (August 2024), post-quantum |
| RSA | Factoring-based public-key system; RFC 8017 (PKCS#1 v2.2) |
| OAEP | Optimal Asymmetric Encryption Padding; required RSA encryption scheme for new apps |
| PSS | Probabilistic Signature Scheme; required RSA signature scheme for new apps |
| PKCS#1 v1.5 | Legacy RSA padding; encryption variant vulnerable to Bleichenbacher |
| Bleichenbacher attack | 1998 padding-oracle attack on RSA PKCS#1 v1.5 encryption |
| P-256 | NIST prime curve secp256r1; 128-bit security |
| Curve25519 | Curve over 2^255 − 19 used by X25519 and Ed25519 |
| X25519 | Diffie-Hellman function on Curve25519 (RFC 7748) |
| Ed25519 | EdDSA signatures on edwards25519 (RFC 8032); deterministic |
| ECDSA | Elliptic Curve DSA; needs a unique secret k per signature |
| RFC 6979 | Deterministic generation of k for DSA/ECDSA |
| Diffie-Hellman (DH) | Key agreement over a public channel; ECDH on curves |
| Forward secrecy | Past sessions stay safe if long-term keys leak; needs ephemeral keys |
| KEM | Key encapsulation mechanism: produces a shared key and its encapsulation for a public key |
| DEM | Data encapsulation mechanism: the symmetric AEAD part of hybrid encryption |
| Hybrid encryption | KEM (asymmetric) for a fresh key + AEAD (symmetric) for the data |
| HPKE | Hybrid Public Key Encryption, RFC 9180 |
| HMAC | Hash-based MAC, RFC 2104 |
| Truncated MAC | Using only the leftmost t bits; RFC 2104 floor is max(80, hash/2) |
| HKDF | HMAC-based extract-then-expand KDF, RFC 5869 |
| PBKDF2 / scrypt / Argon2 | Password-based KDFs with iterations or memory hardness |
| Domain separation | Distinct labels (HKDF info, AAD) so one secret yields independent keys per purpose |
| CSPRNG | Cryptographically secure pseudorandom number generator |
/dev/urandom / getrandom | Linux kernel CSPRNG interfaces; preferred over /dev/random |
| math/rand | Go's non-cryptographic PRNG; predictable |
| UUIDv4 | 122 random bits; an identifier, not a secret |
| Envelope encryption | DEK encrypts data, KEK (in KMS/HSM) encrypts the DEK |
| KMS / HSM | Key management service / hardware security module holding KEKs |
| Key wrapping | Encrypting a key with another key |
| Key rotation | Introducing a new key, re-encrypting, retiring the old one |
| Versioned ciphertext | Ciphertext prefixed with a key ID so the right key is chosen |
| Constant-time comparison | Comparison whose duration does not depend on where inputs differ |
| Timing attack | Recovering secrets from how long operations take |
| secretbox / crypto_box | NaCl/libsodium symmetric and public-key authenticated encryption |
| age | Modern file encryption tool and format: X25519/ML-KEM + HKDF + ChaCha20-Poly1305 |
| sodium | libsodium bindings bundled with PHP 7.2+ (sodium_* functions) |
| Laravel Crypt | Laravel's encrypter: AES-256-CBC + HMAC-SHA256 by default, AES-GCM optional |
| APP_PREVIOUS_KEYS | Laravel setting listing old keys tried on decryption |
References
- Auguste Kerckhoffs, La cryptographie militaire (1883), English rendering of the principles by Fabien Petitcolas: petitcolas.net/kerckhoffs; Shannon's maxim via Wikipedia: Kerckhoffs's principle (secondary)
- NIST: FIPS 197 AES (upd1), SP 800-38A Block Cipher Modes, SP 800-38D GCM, SP 800-57 Part 1 Rev. 5, FIPS 203 ML-KEM, FIPS 204 ML-DSA
- IETF: RFC 2104 HMAC, RFC 4086 Randomness Requirements, RFC 5116 AEAD interface, RFC 5869 HKDF, RFC 6979 Deterministic ECDSA, RFC 7366 Encrypt-then-MAC for TLS, RFC 7748 X25519/X448, RFC 8017 PKCS #1 v2.2, RFC 8032 EdDSA, RFC 8439 ChaCha20-Poly1305, RFC 9180 HPKE, RFC 9562 UUIDs, draft-irtf-cfrg-xchacha-03
- Linux: random(4) man page
- Go (package docs read with
go doc; source links): crypto/cipher gcm.go, crypto/hkdf, crypto/rand text.go, crypto/ecdh; alsocrypto/hmac,crypto/ed25519,crypto/subtle,crypto/mlkem,math/rand/v2,golang.org/x/crypto/nacl/secretbox,golang.org/x/crypto/chacha20poly1305 - PHP manual: sodium_crypto_secretbox, sodium_crypto_box_seal, sodium_crypto_sign_detached, sodium_crypto_sign_verify_detached, sodium_crypto_scalarmult, sodium_crypto_aead_xchacha20poly1305_ietf_encrypt, sodium_crypto_aead_aes256gcm_is_available, hash_hkdf, hash_hmac, hash_equals, random_bytes, openssl_encrypt
- Laravel 13: Encryption, Eloquent: Mutators & Casting (encrypted casts); framework source Encrypter.php, Str.php, UrlGenerator.php, skeleton config/app.php
- HashiCorp: Vault transit secrets engine
- age: README, age v1 specification (C2SP)
- Secondary: Wikipedia: Padding oracle attack (Vaudenay 2002, Lucky Thirteen, POODLE), Wikipedia: Block cipher mode of operation (ECB penguin), Wikipedia: Elliptic Curve Digital Signature Algorithm (PS3, Android Bitcoin wallets)