Skip to content

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 forGo to
Which primitive gives which goal, in one tableEverything in one minute
Why not invent your own schemeWhy cryptography is a toolbox, not a project
Kerckhoffs, Diffie-Hellman, RSA, AES, GCM, Ed25519, ML-KEM datesWhere it comes from
Confidentiality, integrity, authenticity, non-repudiationSecurity goals
AES, block vs stream, ECB, CBC, CTR, GCM, ChaCha20Symmetric encryption and the mode blocks after it
AEAD, AAD, encrypt-then-MACAuthenticated encryption
Nonce vs IV vs key vs saltNonces, IVs, keys and salts
128 vs 256 bits, RSA sizes, post-quantumKey sizes and security levels
RSA-OAEP/PSS, P-256, Curve25519, Ed25519, ECDSAAsymmetric cryptography
DH, ECDH, X25519, forward secrecy, KEM + DEMKey exchange, Hybrid encryption
HMAC vs signature, HKDF vs Argon2MACs vs signatures, KDFs
CSPRNG, /dev/urandom, UUIDv4Randomness
Envelope encryption, rotation, versioned ciphertextsKey hierarchy and rotation
Timing attacks and hmac.Equal / hash_equalsConstant-time comparison
Byte layouts, Laravel Crypt internals, library table, error messagesMechanics
Go + Laravel code for each jobSolving the classic problems
ECB, IV reuse, MAC-then-encrypt, hard-coded keys…Common mistakes
Error → cause → fixTroubleshooting
Which primitive for which jobChoosing
Monolith → microservices → multi-regionIn architecture
ECB penguin, nonce reuse, padding oracle, speedLab

Everything in one minute ​

Goals and the primitive that provides each. Every row is unpacked in the concept catalogue.

GoalIn plain wordsPrimitive that gives itDoes NOT give it
ConfidentialityOnly key holders can read itCipher (AES, ChaCha20), best inside an AEADHash, MAC, signature, Base64
IntegrityAny change is detectedAEAD tag, MAC (HMAC), signatureA cipher alone; a plain hash against an attacker
AuthenticityIt came from someone holding the keyMAC or AEAD (shared key), signature (private key)Encryption alone
Non-repudiationA third party can prove who signedDigital signature (Ed25519, ECDSA, RSA-PSS, ML-DSA)MAC, AEAD: both sides hold the same key

Use this, not that.

JobUseNot
Encrypt data with a secret keyAES-256-GCM or XChaCha20-Poly1305 via a libraryAES-ECB, AES-CBC without MAC, "XOR with a key"
Encrypt to someone's public keyHPKE / age / libsodium crypto_box_seal (X25519 + AEAD)Raw RSA, RSA PKCS#1 v1.5 encryption
Prove a message came from your service to anyoneEd25519 signatureHMAC (verifiers could forge)
Authenticate a webhook between two partiesHMAC-SHA256 + constant-time compare + timestampsha256(secret + body), == comparison
Turn a shared secret into keysHKDF with a distinct info per useUsing the raw ECDH output as a key
Store passwordsArgon2id / bcrypt (see password hashing)SHA-256, HKDF, encryption
Generate tokens, keys, noncescrypto/rand, random_bytes(), /dev/urandommath/rand, mt_rand(), uniqid(), time
Compare secretshmac.Equal, subtle.ConstantTimeCompare, hash_equals==, bytes.Equal, strcmp

The three numbers you must never confuse.

ThingSecret?Must be unique?Must be random?Typical size
KeyYesPer purposeYes (or derived by a KDF)16 or 32 bytes symmetric
Nonce / IVNo, sent in clearYes, per key, foreverGCM: unique (random OK below 2^32 messages); CBC IV: unpredictable12 bytes GCM, 24 bytes XChaCha20, 16 bytes CBC
SaltNo, stored in clearShould beYes16 bytes or more
Primitive → security goalConfidentialityIntegrityAuthenticityNon-repudiationBlock/stream cipher aloneAES-CBC, AES-CTR, ChaCha20yesnononoAEADAES-GCM, ChaCha20-Poly1305yesyesshared-key onlynoHashSHA-256, SHA-3, BLAKE3noonly vs accidentsnonoMACHMAC-SHA256, Poly1305noyesshared-key onlynoDigital signatureEd25519, ECDSA, RSA-PSSnoyesyesyesKey exchangeX25519, ECDH P-256, ML-KEMenables itnononoKDFHKDF; Argon2 for passwordsenables itnononoCSPRNGcrypto/rand, random_bytesenables itnonono"shared-key only": anyone holding the key could have produced the tag, so it proves "one of us", not "who"."enables it": produces or agrees on the key; confidentiality itself still comes from the cipher.

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, Poly1305RSA, ECDH/X25519, Ed25519, ECDSA, ML-KEM, ML-DSA
Fast: about 200 ns to seal 1 KiB with AES-GCM on our machineSlow: 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 partPublic key can be published; only the private key is secret
Gives confidentiality, integrity, shared-key authenticityGives key agreement, signatures, non-repudiation
Used for bulk dataUsed 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 ​

  1. "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.
  2. "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).
  3. "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 from math/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.

LayerRoll your own?Use instead
Cipher, hash, curveNeverAES, ChaCha20, SHA-2/3, BLAKE3, X25519, Ed25519
Mode / construction (cipher + MAC, nonce scheme)NeverAEAD: AES-GCM, ChaCha20-Poly1305; libsodium secretbox
Protocol (handshake, token format, file format)Almost neverTLS 1.3, HPKE (RFC 9180), age, PASETO, JWT with a fixed algorithm
Key management (where keys live, who rotates them)Yes, this is your jobKMS/HSM/Vault plus your own rotation runbook
Calling the library correctlyYes, this is your jobThis page

Where it comes from ​

YearEventWhy it matters today
1883Kerckhoffs, La cryptographie militaireSecurity must rest on the key, not on a secret design
1949Shannon, "Communication Theory of Secrecy Systems"Mathematical basis of ciphers; "the enemy knows the system"
1976Diffie and Hellman, "New Directions in Cryptography"Public-key key agreement: two parties agree a secret over a public channel
1977RSA; DES standardisedFirst practical public-key encryption and signatures; first standard block cipher
1997HMAC, RFC 2104 (February)The keyed MAC used by webhooks, JWT HS256, TLS 1.2 PRF, HKDF
1998Bleichenbacher's attack on RSA PKCS#1 v1.5 encryptionWhy RFC 8017 keeps v1.5 "only for compatibility"
2001AES, FIPS 197 (published November 26, 2001; updated May 9, 2023)The block cipher used everywhere today
2002Vaudenay's CBC padding oracle (EUROCRYPT 2002, via secondary sources)Why unauthenticated CBC is broken in practice
2007GCM, NIST SP 800-38D (November 2007)The dominant AEAD; 96-bit IVs; the uniqueness rule
2010HKDF, RFC 5869 (May)Standard way to derive many keys from one secret
2013RFC 6979 deterministic ECDSA (August)Removes the "random k" failure that leaks ECDSA keys
2016X25519, RFC 7748 (January); PKCS#1 v2.2, RFC 8017 (November)Modern key agreement; OAEP and PSS required for new apps
2017Ed25519, RFC 8032 (January)Deterministic, fast, small signatures
2018ChaCha20-Poly1305, RFC 8439 (June)The AEAD for platforms without AES hardware; TLS 1.3 cipher suite
2022HPKE, RFC 9180 (February)Standard hybrid public-key encryption (KEM + KDF + AEAD)
2024FIPS 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.

text
     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 / APIConfidentialityIntegrity + authenticityNon-repudiation
Go crypto/cipher NewCTR, NewCBCEncrypterYesNoNo
Go cipher.NewGCM, x/crypto/chacha20poly1305YesYes (shared key)No
Go crypto/hmac, PHP hash_hmacNoYes (shared key)No
Go crypto/ed25519, PHP sodium_crypto_sign_detachedNoYesYes
Laravel Crypt (AES-256-CBC + HMAC, or AES-GCM)YesYes (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".

KindExamplesUnitNeeds padding?Parallel?
Block cipher in ECB/CBCAES-ECB, AES-CBC16-byte blocksYes (PKCS#7)ECB both ways; CBC decrypt only
Block cipher as a stream (counter)AES-CTR, AES-GCMByteNoYes
Native stream cipherChaCha20, XChaCha20, Salsa20ByteNoYes

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).

text
     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   <- different

Real 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.

LibraryECB available?
Go crypto/cipherNo mode; you would have to loop Block.Encrypt yourself (do not)
PHP openssl_encryptYes: aes-128-ecb, aes-256-ecb
Laravel CryptNo: only aes-128-cbc, aes-256-cbc, aes-128-gcm, aes-256-gcm
OpenSSL CLIYes: 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.

text
     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 plaintext

Real 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").

ProductDefaultProtected against padding oracles?
Laravel Crypt with AES-256-CBC (13.x default)Encrypt-then-MACYes: HMAC-SHA256 is checked with hash_equals before openssl_decrypt runs
Raw openssl_decrypt('aes-256-cbc')No MACNo, unless you add encrypt-then-MAC
Go NewCBCDecrypterNo MAC, no padding helperNo; you write padding yourself
TLS 1.3No CBC suites at allYes

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."

text
     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.

ProductNonce handlingNotes
Go cipher.NewGCMYou supply 12 bytesStandard; prepend the nonce to the ciphertext yourself
Go cipher.NewGCMWithRandomNonce (1.24+)Generated and prepended; Overhead() is 282^32 messages per key
Go NewGCMWithNonceSize, NewGCMWithTagSizeNon-standard sizes"Only use this function if you require compatibility"
PHP openssl_encrypt('aes-256-gcm')You supply $iv; $tag by referencetag_length 4–16; keep 16
PHP sodium_crypto_aead_aes256gcm_encryptYou supply 12 bytesOnly if sodium_crypto_aead_aes256gcm_is_available() (hardware AES)
Laravel Crypt with AES-256-GCMRandom 12-byte IV per valueTag 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."

ConstructionKeyNonceTagWhere
ChaCha20-Poly1305 (RFC 8439)32 B12 B16 BTLS 1.3, WireGuard, SSH, Go chacha20poly1305.New
XChaCha20-Poly130532 B24 B16 Blibsodium (sodium_crypto_aead_xchacha20poly1305_ietf_encrypt, "Preferred" in the PHP manual), Go chacha20poly1305.NewX
NaCl secretbox (XSalsa20-Poly1305)32 B24 B16 BGo x/crypto/nacl/secretbox, PHP sodium_crypto_secretbox
age payload32 B (HKDF from file key)12 B counter per 64 KiB chunk16 Bage 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.

AEAD (AES-GCM, ChaCha20-Poly1305): one call encrypts and authenticatesKey (secret, 16 or 32 B)Nonce (12 B GCM, 24 B X*)PlaintextAAD (header, ids, version)Sealencrypt + MACCiphertext (= len)Tag (16 B)Nonce and AAD travel in the clearkey, nonce, AAD, ciphertext, tagOpenplaintextor error onlySame key + same nonce twice = keystream reuse (XOR of plaintexts leaks) and, for GCM, forgeable tags.

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.

CompositionWho uses itVerdict
Encrypt-then-MAC (MAC over IV + ciphertext, separate key)Laravel Crypt CBC mode (same key for both), IPsec ESP, RFC 7366 for TLSSafe if MAC is checked first in constant time
MAC-then-encryptTLS up to 1.2 with CBC suitesSource of padding-oracle class bugs (Lucky Thirteen 2013, POODLE 2014, per Wikipedia)
Encrypt-and-MAC (MAC over plaintext, sent alongside)Some older protocol designsA deterministic MAC on plaintext leaks plaintext equality
AEAD (GCM, ChaCha20-Poly1305)TLS 1.3, QUIC, WireGuard, ageDefault 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.

ValueSecret?RuleRepeated →Store itSize
Symmetric keyYesRandom 128/256 bits; one key per purposen/aKMS, secret store, never Git16/32 B
GCM nonceNoUnique per key, foreverPlaintext XOR leaks, tag forgeryPrepended to ciphertext12 B
XChaCha20 nonceNoUnique per key; random is fineSame as above (but collisions are negligible)Prepended24 B
CBC IVNoUnpredictable (random) per messageEqual prefixes leak equalityPrepended16 B
CTR initial counterNoCounter blocks never overlapKeystream reusePrepended16 B
KDF salt (HKDF)NoRandom if available; may be reusedWeaker extraction onlyNext to output or fixed per app32 B (HashLen)
Password saltNoUnique per passwordRainbow tables, equal hashes visibleInside the hash string16 B
ECDSA per-signature kYesUnique, uniformly random or RFC 6979Private key recoveredNever stored32 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)SymmetricRSA / finite-field DHElliptic curve (ECDSA, EdDSA, ECDH)
112(3TDEA, deprecated)2048224–255
128AES-1283072256–383 (P-256)
192AES-1927680384–511 (P-384)
256AES-25615360512+ (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:

AlgorithmUsePadding / variant to useAvoidSizes
RSA encryptionWrap a keyRSAES-OAEP: "REQUIRED to be supported for new applications" (RFC 8017)RSAES-PKCS1-v1_5: "included only for compatibility"; Bleichenbacher2048 min, 3072 for 128-bit
RSA signatureJWT RS256/PS256, code signing, X.509RSASSA-PSS: "REQUIRED in new applications"PKCS#1 v1.5 signatures only for compatibility (no known attack)256–384 B signatures
ECDSA P-256X.509 certs, ES256 JWT, AWS/GCP KMS keysRFC 6979 deterministic k, or a CSPRNG kReusing or biasing k32 B key, 64–72 B signature
Ed25519 (EdDSA, RFC 8032)SSH keys, release signing, PASETO v4, age/minisignPure Ed25519Exposing the 64-byte private key format confusion32 B public key, 64 B signature
X25519 (RFC 7748)Key agreement (TLS 1.3, WireGuard, Signal, age)Reject all-zero shared secretUsing the raw output as a key32 B keys
ECDH P-256FIPS environments, TLSValidate points (Go crypto/ecdh does)Invalid-curve points from untrusted input32 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.

text
     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 key

This 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.

text
     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
WhereKey exchangeAuthenticated by
TLS 1.3ECDHE X25519 / P-256, hybrid X25519MLKEM768Certificate signature over the handshake (see TLS in Practice)
WireGuardNoise IK with X25519Static public keys configured on both ends
SSHcurve25519-sha256, sntrup761x25519Host key signature, user key
ageX25519 recipient, ephemeral sender keyNot 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.

Sender (has recipient public key only)Recipient (has its private key)1. ephemeral X25519 pair (eph_priv, eph_pub)2. shared = X25519(eph_priv, recip_pub)3. key = HKDF(shared, info = label+eph_pub+recip_pub)4. AES-256-GCM.Seal(key, data, aad)recip_priv (stays in KMS / secret store)5. shared = X25519(recip_priv, eph_pub)6. same HKDF with the same info = same key7. AES-256-GCM.Open → plaintext or erroreph_pub (32 B)ciphertext (len of data)tag (16)Wire message. eph_priv is discarded after step 4: stealing recip_priv later still opens old messages(no forward secrecy for stored data); interactive protocols such as TLS 1.3 make BOTH sides ephemeral to get it.Same shape: ECIES, HPKE base mode (RFC 9180), age X25519 recipients, libsodium crypto_box_seal.

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.

SchemeKEMKDFAEADNotes
HPKE base mode (RFC 9180)DHKEM(X25519, HKDF-SHA256) or DHKEM(P-256, HKDF-SHA256)HKDF-SHA256AES-128-GCM, AES-256-GCM, ChaCha20Poly1305Used by TLS ECH, MLS
ageX25519 (or hybrid ML-KEM-768 + X25519 in 1.3.0+)HKDF-SHA-256ChaCha20-Poly1305, 64 KiB chunksFile encryption CLI and Go library
libsodium crypto_box_sealX25519 ephemerallibsodium internalXSalsa20-Poly1305"Anonymous public-key encryption" (PHP manual)
Cloud KMS envelopeKMS-held key wraps a data keyn/aAES-GCM data keySee envelope encryption
Our example (code)X25519 ephemeralHKDF-SHA256, info binds both keysAES-256-GCMTeaching 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".

PropertyHMAC-SHA256Ed25519 signature
KeysOne shared secretPrivate (signer) + public (everyone)
Who can verifyKey holders onlyAnyone with the public key
Who can forgeEvery verifierOnly the private-key holder
Non-repudiationNoYes
SpeedHash speed (not benchmarked here)12 µs sign, 25 µs verify in our run
Typical useWebhooks between two parties, cookies, signed URLs, JWT HS256Releases, 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.

text
     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
KDFInputCost knobWhere
HKDF (RFC 5869)High-entropy secretNone (fast)TLS 1.3 key schedule, HPKE, age, Signal; Go crypto/hkdf (1.24+); PHP hash_hkdf
PBKDF2PasswordIterationsLegacy, FIPS; Go crypto/pbkdf2 (1.24+)
scryptPasswordN, r, p (memory-hard)Go x/crypto/scrypt, PHP sodium pwhash_scryptsalsa208sha256
Argon2id (RFC 9106)PasswordMemory, iterations, parallelismGo x/crypto/argon2, PHP password_hash(PASSWORD_ARGON2ID), Laravel Hash
KMAC / SP 800-108 KDFsHigh-entropy secretNoneFIPS 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.

text
     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 / toolCSPRNGNot for secrets
Gocrypto/rand.Read, rand.Text, rand.Intmath/rand, math/rand/v2 (even ChaCha8 source when seeded predictably)
PHP / Laravelrandom_bytes, random_int, Str::random (built on random_bytes), Str::uuid (v4)rand, mt_rand, uniqid, str_shuffle, lcg_value
Shellopenssl rand -hex 32, head -c 32 /dev/urandom$RANDOM
Linux kernelgetrandom(2), /dev/urandomn/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.

text
     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"
sql
-- 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;
ProductKey ID in ciphertext?Rotation model
Our Keyring / VersionedEncrypterYes, 1 byte, authenticatedAdd key, switch current, re-encrypt, retire
Laravel Crypt + APP_PREVIOUS_KEYSNoTry each key; sessions survive rotation
HashiCorp Vault transitYes (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()."

text
     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
LanguageConstant-time compareNot constant-time
Gohmac.Equal, subtle.ConstantTimeCompare== on strings, bytes.Equal
PHPhash_equals($known, $user) ("Timing attack safe string comparison")==, ===, strcmp
LaravelCrypt uses hash_equals for the MAC; UrlGenerator signed-URL checks use hash_equalsComparing 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 ​

  1. 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."
  2. 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.
  3. Ciphertext = plaintext XOR AES(k, J0+1), AES(k, J0+2), …
  4. S = GHASH_H(AAD padded ‖ ciphertext padded ‖ len(AAD) ‖ len(C)); tag = MSB_t(AES(k, J0) XOR S).
  5. 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):

text
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):

text
$ 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..../......Q

PKCS#7 padding seen from the inside (decrypt without removing padding): "hi" plus 14 bytes of 0x0e.

text
$ 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:

AspectBehaviour
Configured cipherconfig/app.php: 'cipher' => 'AES-256-CBC'; the docs: "All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher"
Supported ciphersaes-128-cbc, aes-256-cbc, aes-128-gcm, aes-256-gcm (constructor default argument is aes-128-cbc; the app config overrides it)
KeyAPP_KEY, raw length must be 16 or 32 bytes for the cipher; php artisan key:generate uses random_bytes
IVrandom_bytes(openssl_cipher_iv_length(...)): 16 bytes for CBC, 12 for GCM
CBC integrityhash_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 integritymac field is ''; the 16-byte tag is in tag; a tag of another length is rejected; no AAD is passed
Payloadbase64(json_encode(['iv','value','mac','tag']))
Serialisationencrypt() calls serialize(), encryptString() does not
RotationAPP_PREVIOUS_KEYS (comma-separated); encryption uses APP_KEY; decryption tries every key; no key ID in the payload
ErrorsDecryptException: "The payload is invalid.", "The MAC is invalid.", "Could not decrypt the data."; RuntimeException "Unsupported cipher or incorrect key length"
Eloquentencrypted, 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 ​

JobGo stdlib / x/cryptoPHP / LaravelCLI
AES-GCMcrypto/aes + cipher.NewGCM, NewGCMWithRandomNonceopenssl_encrypt('aes-256-gcm'), sodium_crypto_aead_aes256gcm_* (if hardware), Crypt with GCM cipheropenssl enc does not support AEAD modes; use age or a script
ChaCha20-Poly1305 / XChaCha20x/crypto/chacha20poly1305 New, NewXsodium_crypto_aead_chacha20poly1305_ietf_*, sodium_crypto_aead_xchacha20poly1305_ietf_*age
Secret box (hard to misuse)x/crypto/nacl/secretboxsodium_crypto_secretboxn/a
Public-key boxx/crypto/nacl/box (Seal, SealAnonymous)sodium_crypto_box, sodium_crypto_box_sealage
X25519 / ECDHcrypto/ecdhsodium_crypto_scalarmult, sodium_crypto_kx_*openssl pkeyutl -derive (OpenSSL 3)
Ed25519crypto/ed25519sodium_crypto_sign_detached, _verify_detachedssh-keygen -t ed25519, openssl genpkey -algorithm ed25519 (OpenSSL 3; LibreSSL 3.3.6 says "Algorithm ed25519 not found")
ECDSA / RSAcrypto/ecdsa, crypto/rsa (SignPSS, EncryptOAEP)openssl_sign, openssl_public_encrypt with OPENSSL_PKCS1_OAEP_PADDINGopenssl pkeyutl
HMACcrypto/hmac + hmac.Equalhash_hmac + hash_equalsopenssl dgst -sha256 -hmac
HKDFcrypto/hkdf (1.24+), x/crypto/hkdfhash_hkdfopenssl kdf (OpenSSL 3)
Randomcrypto/randrandom_bytes, random_int, Str::randomopenssl rand, /dev/urandom
Post-quantumcrypto/mlkem (1.24+)none in core PHP 8.4age 1.3.0+ -pq keys
File encryptionfilippo.io/ageshell out to age, or sodium secretstreamage

Error messages you will see Must-know ​

MessageWhereMeaning
cipher: message authentication failedGo AEAD.OpenWrong key, wrong nonce, wrong AAD, or tampered data; never "partially decrypted"
crypto/aes: invalid key size 20Go aes.NewCipherKey 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 pointGo PrivateKey.ECDHMalicious or corrupt peer key producing the all-zero secret
crypto/ecdh: invalid public keyGo NewPublicKeyWrong length or not on the curve
crypto/rsa: decryption errorGo DecryptOAEPWrong key or label, tampered ciphertext; deliberately generic
openssl_decrypt(): ... returns falsePHPSame 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.LaravelNot base64 JSON with iv, value, mac, or IV of wrong length
Unsupported cipher or incorrect key length.Laravel bootAPP_KEY missing its base64: prefix or wrong length for the cipher
SodiumException on encryptPHP sodiumNonce 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 ​

ProblemSolutionHowAdvantageCost / limitation
Encrypt a field in the databaseAES-256-GCM with versioned key ring and AADversion + nonce + ct + tag, AAD = version + "table.column:id"Rotation without guessing; copy-paste between rows detectedNot searchable (add a blind index)
Encrypt for a party that has only published a public keyHybrid: X25519 + HKDF + AEAD (or HPKE / age / crypto_box_seal)Ephemeral key per messageOnly recipient decrypts; fast for big dataNo sender authentication unless you also sign
Prove origin to many consumersEd25519 signatureSign canonical bytes; distribute the public keyConsumers cannot forgeKey distribution and revocation
Authenticate webhooks between two partiesHMAC-SHA256 over timestamp + bodyConstant-time compare, tolerance windowSimple, fastShared secret on both sides
Tokens and keysCSPRNG, 32 bytescrypto/rand, random_bytesUnguessableStore only a hash of long-lived tokens
Default encryption with fewest footgunslibsodium secretbox / XChaCha20-Poly1305, Laravel CryptRandom 24-byte noncesNo nonce budgetingInterop 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.

go
// 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
<?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:

text
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: 1

Encrypt to a public key: X25519 + HKDF hybrid ​

go
// 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
<?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);
    }
}
text
message: 69 bytes = 32 ephemeral pub + 21 ciphertext + 16 tag
decrypted: "card=4111111111111111" err=<nil>
tampered: cipher: message authentication failed

For 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 ​

go
// 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
<?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']); // true
text
public key 32 bytes, signature 64 bytes
sig: oC_a8SjVFg126mvx2vQu3GlJRHQAOoi2uxO26xWZSUnMHnL2pIrvsfOiuDzCDwdM9IZzxM_nOIT-dOXOyf7xAg
valid: true
after tampering: false

Sign 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 ​

go
// 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
<?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);
    }
}
text
t=1764000000,v1=083da225651d93f0e4002fd6f1cfbdd18d0b8091ce4ccd8c63b25da4c8dfdd62
ok: <nil>
tampered: signature mismatch
replayed later: timestamp outside tolerance

Verify 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 ​

go
// 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
<?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.
}
text
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 ​

go
// 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
<?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'] ?? '') !== '',
        ];
    }
}
text
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 ​

MistakeWhat breaksSeen asFix
ECB modeEqual blocks leak, blocks can be cut and pastedaes-*-ecb in PHP/OpenSSL codeAEAD
IV / nonce reuse (GCM, CTR, ChaCha20)XOR of plaintexts; GCM tag forgeryConstant nonce, counter reset on restart, timestamp nonceRandom nonce + rotation budget, persisted counter, XChaCha20
Unauthenticated CBC / CTRBit flipping, padding oracleopenssl_encrypt('aes-256-cbc') with no MACAEAD or encrypt-then-MAC
MAC-then-encryptReceiver decrypts before checkingCustom "encrypt(json + hmac)" formatsEncrypt-then-MAC or AEAD
Truncated MACFewer bits to guessComparing first 8 hex chars of a tagFull 32-byte HMAC-SHA256 (≥ 128 bits)
== comparison of MACs/tokensTiming attackif ($sig === $expected)hash_equals, hmac.Equal
RSA PKCS#1 v1.5 encryptionBleichenbacher padding oracleOPENSSL_PKCS1_PADDING, rsa.EncryptPKCS1v15OAEP, or better a KEM (X25519/HPKE)
Raw ECDH output as keyBiased, context-free keykey := sharedHKDF with info
Same key for two purposesCross-protocol attacks, rotation couplingOne APP_KEY for encryption, MAC and signed URLsSeparate keys or HKDF domain separation
ECDSA with bad randomnessPrivate key recoveryCustom k, broken RNG on embedded devicesEd25519 or RFC 6979 / hedged ECDSA
Home-made protocolsUnknown"We XOR with a rotating key", custom handshakeTLS, HPKE, age, PASETO
Hard-coded keysEveryone with repo access, CI logs, Docker layers has the keyconst key = "...", .env committedKMS / secret manager, rotation
Logging plaintext or keysSecret in log pipeline foreverLog::debug($request->all()), panics printing structsRedaction, #[\SensitiveParameter], typed secrets
math/rand / mt_rand for tokensPredictable tokensReset links, invite codes, OTPscrypto/rand, random_bytes, random_int
Hash as password storageFast brute forcesha256($password)Argon2id/bcrypt (page)
No key ID in ciphertextRotation by trial and errorLaravel-style payloads at scaleVersion byte or key ID in AAD

Troubleshooting ​

SymptomLikely causeCheckFix
Every decryption fails after deployNew APP_KEY / key not loadedCompare key fingerprint (HMAC of a constant) across hostsPut old key in APP_PREVIOUS_KEYS / key ring
Decryption fails only for some rowsValue copied between rows or contexts (AAD mismatch)Log context used at encrypt vs decryptRe-encrypt with the right context
invalid key sizeHex or base64 string passed as raw keylen(key) is 44/64 instead of 32Decode first; Laravel needs the base64: prefix
Go encrypts, PHP cannot decryptDifferent layout (nonce position, tag appended vs separate), different HKDF argument orderHex-dump both sidesDocument 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 valueUse the library unpadding, or AEAD
Signature valid locally, invalid at consumerBytes differ (JSON re-serialisation, newline, encoding)Hash the exact bytes on both sidesSign and verify the raw transmitted bytes
Webhooks fail intermittentlyClock skew or body modified by middlewareCompare server time; log raw body lengthNTP; read raw body before parsing
Same "random" tokens across podsPRNG seeded with a constant or time at startGrep for math/rand, mt_srandCSPRNG
Duplicate GCM nonces in auditCounter in memory, multiple writersCount nonces per key in logsRandom nonces with budget, or per-writer prefix
sodium_crypto_aead_aes256gcm_* throws on some serversCPU without AES-NI / ARM buildsodium_crypto_aead_aes256gcm_is_available()XChaCha20-Poly1305 or openssl GCM

Choosing ​

SituationRecommendationExtra techniqueReason
Encrypting fields in one appAES-256-GCM (Go) / Laravel Crypt with GCM or CBC+MACVersion byte + AAD with record contextFast, hardware accelerated, rotation-ready
Many writers, high volume, no coordinationXChaCha20-Poly1305Random 24-byte noncesNo nonce budget to track
No AES hardware (old ARM, IoT)ChaCha20-Poly1305n/aAbout 3x faster in software (RFC 8439)
Encrypt to a recipient's public keyHPKE / age / crypto_box_sealSign too if sender identity mattersStandard formats, reviewed
Signatures, greenfieldEd25519Canonical bytesDeterministic, fast, small
Signatures under FIPS / X.509 / cloud KMSECDSA P-256 or RSA-PSS 3072RFC 6979 or hedged kApproved algorithms
Two-party message authenticationHMAC-SHA256Timestamp + constant-time compareSimple, no PKI
Derive several keys from one secretHKDF-SHA256One info label per purposeDomain separation
PasswordsArgon2id / bcryptPer-user salt (built in)Slow by design
Long-lived secrets vs future quantum attackersHybrid X25519 + ML-KEM-768AES-256 data keys"Harvest now, decrypt later" protection
Compliance needs key custodyEnvelope encryption with KMS/HSMKey IDs, audit logsKEK 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.

text
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× ​

LoadWhat changesCrypto consequence
1× (one app, one DB)APP_KEY + a few secretsLaravel Crypt or one Go key ring; HMAC webhooks; CSPRNG tokens
10× (several services, queues)Many verifiers, more writersSignatures 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, auditsEnvelope 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 ​

go
// 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)
}
text
$ 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 ​

go
// 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)
}
text
$ 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 ​

go
// 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)
}
text
$ 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 blocks

About 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 ​

go
// 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)
		}
	})
}
text
$ 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/op

Read 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 ​

bash
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 | xxd
text
d597d45685028e37ea6c6e6209cf16811134685a1adb5fcd8b68465303b51bf7
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 ​

  1. In aeadkeys, change the context in Decrypt and watch cipher: message authentication failed.
  2. In hmacsig, replace hmac.Equal with string(got) == string(mac.Sum(nil)): tests still pass, which is exactly why reviewers must look for it.
  3. In hybrid, drop recipientPub from 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 ​

BeliefReality
Encryption gives integrityOnly AEAD, encrypt-then-MAC or signatures do; CTR/CBC alone can be modified
A secret algorithm adds securityKerckhoffs: assume the design is known; secrecy belongs to the key
AES-256 means 256-bit security for my systemThe weakest link is the mode, the nonce, the key storage or the comparison
Random GCM nonces are safe forever2^32 messages per key, then rotate, or use XChaCha20
HMAC is a signatureEvery verifier can forge; no non-repudiation
RSA can encrypt filesOnly small payloads; use hybrid encryption
The ECDH shared secret is a keyRun it through HKDF with context
HKDF makes passwords strongIt cannot add entropy; use Argon2id/bcrypt
/dev/random is better than /dev/urandomLegacy; /dev/urandom/getrandom(2) is the right source
UUIDv4 is a secretRFC 9562: must not be used as a security capability
Base64 or hex is encryptionIt is encoding; anyone decodes it
Rotating a key re-encrypts the dataOnly new data; old ciphertexts need a re-encryption job and a key ID
Timing attacks are theoretical over a networkRFC 8439 makes constant-time tag comparison a MUST

Cheat sheet ​

TopicRemember
Default symmetricAES-256-GCM or XChaCha20-Poly1305 through a library
GCM nonce12 bytes, unique per key; random OK up to 2^32 messages
XChaCha20 nonce24 bytes, random is fine
AADBind context: record ID, column, key version, tenant
NeverECB, unauthenticated CBC/CTR, MAC-then-encrypt, PKCS#1 v1.5 encryption
SignaturesEd25519; ECDSA P-256 with RFC 6979; RSA-PSS for compatibility
Key exchangeX25519 → HKDF; ephemeral both sides for forward secrecy
Public-key encryptionHybrid: HPKE, age, crypto_box_seal
MAC vs signatureMAC = shared key, verifiers can forge; signature = anyone verifies, only signer signs
KDFHKDF with distinct info per purpose; Argon2id/bcrypt for passwords
Randomcrypto/rand, random_bytes; never math/rand, mt_rand
Comparehmac.Equal, hash_equals
RotationKey ID in ciphertext, re-encrypt job, retire after backups age out
Security levelsAES-128 ≈ RSA-3072 ≈ P-256; RSA-2048 = 112 bits
Post-quantumML-KEM (FIPS 203), ML-DSA (FIPS 204); hybrid X25519MLKEM768 now
Laravel CryptAES-256-CBC + HMAC-SHA256 by default, GCM optional, no AAD, no key ID

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
ConfidentialityOnly authorised key holders can read the data
IntegrityUnauthorised changes are detected
AuthenticityThe data provably came from a holder of a specific key
Non-repudiationA third party can verify who signed; needs a digital signature
Kerckhoffs's principleA system must stay secure when everything except the key is public
Don't roll your ownUse reviewed primitives, constructions and protocols through vetted libraries
Block cipherKeyed permutation of fixed-size blocks; AES uses 128-bit blocks
Stream cipherGenerates a keystream XORed with data; ChaCha20, AES-CTR
AES-128 / AES-256AES with 128- or 256-bit keys (10 or 14 rounds), FIPS 197
ECBElectronic Codebook: each block encrypted independently; leaks patterns (the penguin)
CBCCipher Block Chaining: each block XORed with the previous ciphertext; needs padding and a random IV
PKCS#7 paddingn bytes of value n to fill the last block
Padding oracleAny signal revealing whether padding was valid; decrypts CBC without the key (Vaudenay 2002)
CTRCounter mode: encrypt a counter, XOR with data
GCMGalois/Counter Mode: CTR + GHASH tag; NIST SP 800-38D
GHASHPolynomial hash over GF(2^128) keyed by H = AES(k, 0)
Poly1305One-time polynomial MAC modulo 2^130 − 5, keyed from ChaCha20 in the AEAD
ChaCha20-Poly1305RFC 8439 AEAD: 32-byte key, 12-byte nonce, 16-byte tag
XChaCha20ChaCha20 with a 24-byte nonce via HChaCha20; safe with random nonces
AEADAuthenticated Encryption with Associated Data: one call for confidentiality and integrity
AADAssociated data: authenticated, not encrypted (headers, IDs, key version)
TagThe MAC output of an AEAD, usually 16 bytes
Encrypt-then-MACMAC computed over the ciphertext with a separate key; checked before decrypting
MAC-then-encryptMAC over plaintext, then encrypted; source of padding-oracle bugs
NonceNumber used once per key; public
IVInitialisation vector; public per-message input to a mode
SaltPublic random input to a KDF or password hash
2^32 limitMax messages per AES-GCM key with random 96-bit nonces (NIST, Go docs)
Security levellog2 of the cost of the best known attack (112, 128, 192, 256 bits)
ML-KEMModule-lattice KEM, FIPS 203 (August 2024), post-quantum
ML-DSAModule-lattice signature, FIPS 204 (August 2024), post-quantum
RSAFactoring-based public-key system; RFC 8017 (PKCS#1 v2.2)
OAEPOptimal Asymmetric Encryption Padding; required RSA encryption scheme for new apps
PSSProbabilistic Signature Scheme; required RSA signature scheme for new apps
PKCS#1 v1.5Legacy RSA padding; encryption variant vulnerable to Bleichenbacher
Bleichenbacher attack1998 padding-oracle attack on RSA PKCS#1 v1.5 encryption
P-256NIST prime curve secp256r1; 128-bit security
Curve25519Curve over 2^255 − 19 used by X25519 and Ed25519
X25519Diffie-Hellman function on Curve25519 (RFC 7748)
Ed25519EdDSA signatures on edwards25519 (RFC 8032); deterministic
ECDSAElliptic Curve DSA; needs a unique secret k per signature
RFC 6979Deterministic generation of k for DSA/ECDSA
Diffie-Hellman (DH)Key agreement over a public channel; ECDH on curves
Forward secrecyPast sessions stay safe if long-term keys leak; needs ephemeral keys
KEMKey encapsulation mechanism: produces a shared key and its encapsulation for a public key
DEMData encapsulation mechanism: the symmetric AEAD part of hybrid encryption
Hybrid encryptionKEM (asymmetric) for a fresh key + AEAD (symmetric) for the data
HPKEHybrid Public Key Encryption, RFC 9180
HMACHash-based MAC, RFC 2104
Truncated MACUsing only the leftmost t bits; RFC 2104 floor is max(80, hash/2)
HKDFHMAC-based extract-then-expand KDF, RFC 5869
PBKDF2 / scrypt / Argon2Password-based KDFs with iterations or memory hardness
Domain separationDistinct labels (HKDF info, AAD) so one secret yields independent keys per purpose
CSPRNGCryptographically secure pseudorandom number generator
/dev/urandom / getrandomLinux kernel CSPRNG interfaces; preferred over /dev/random
math/randGo's non-cryptographic PRNG; predictable
UUIDv4122 random bits; an identifier, not a secret
Envelope encryptionDEK encrypts data, KEK (in KMS/HSM) encrypts the DEK
KMS / HSMKey management service / hardware security module holding KEKs
Key wrappingEncrypting a key with another key
Key rotationIntroducing a new key, re-encrypting, retiring the old one
Versioned ciphertextCiphertext prefixed with a key ID so the right key is chosen
Constant-time comparisonComparison whose duration does not depend on where inputs differ
Timing attackRecovering secrets from how long operations take
secretbox / crypto_boxNaCl/libsodium symmetric and public-key authenticated encryption
ageModern file encryption tool and format: X25519/ML-KEM + HKDF + ChaCha20-Poly1305
sodiumlibsodium bindings bundled with PHP 7.2+ (sodium_* functions)
Laravel CryptLaravel's encrypter: AES-256-CBC + HMAC-SHA256 by default, AES-GCM optional
APP_PREVIOUS_KEYSLaravel setting listing old keys tried on decryption

References ​

Built by Morteza Negahi