Skip to content

Cryptography in Practice: Symmetric vs Asymmetric, TLS/HTTPS, PKI, Encryption at Rest, Secrets ​

"Envelope encryption is the practice of encrypting plaintext data with a data key, and then encrypting the data key under another key." — AWS Key Management Service Developer Guide, AWS KMS cryptography essentials: Envelope encryption

Summary: Cryptography in a real system is a set of decisions, not a set of algorithms: which primitive for which job, who holds which key, where plaintext exists, how keys and certificates rotate without an outage, and how secrets reach a process without ending up in git, logs or images. Focus: Symmetric vs asymmetric encryption, choosing primitives by use case (AES-256-GCM, ChaCha20-Poly1305, X25519, Ed25519, ECDSA, RSA-PSS, RSA-OAEP, HKDF, HMAC-SHA-256, Argon2id) and what to avoid, nonce/IV limits at scale, envelope encryption with DEK/KEK and a KMS, key hierarchy, rotation, re-wrap, crypto-shredding, HSM and FIPS 140-3, the layers of encryption at rest, TLS 1.3 policy and termination points, mTLS and pinning, PKI (CAs, chains, CSR, SAN, the 398 to 47 day validity schedule, CRL/OCSP/stapling, short-lived certificates, Certificate Transparency, ACME), private PKI (step-ca, Vault PKI, cert-manager, SPIFFE/SPIRE), secrets management (Vault, AWS Secrets Manager and Parameter Store, GCP Secret Manager, sealed-secrets, External Secrets Operator, SOPS, age), dynamic secrets and leases, injection patterns, secret sprawl scanning, artefact signing (Sigstore, cosign, SLSA), randomness and honest compliance claims. Learning goal: For any system, pick the primitive and the layer that match the threat, design a key hierarchy with a rotation and destruction story, set a TLS and certificate policy that survives 47-day certificates, choose how each secret is stored, injected and rotated, and implement envelope encryption, a modern TLS configuration and a secrets loader in Go and Laravel.

This chapter is the system-level view. The primitives themselves (block modes, what a nonce is inside GCM, how ECDH and signatures work) are in Cryptography Fundamentals; the TLS handshake on the wire, SNI/ALPN and openssl s_client debugging are in TLS in Practice; the database encryption layers (TDE internals, pgcrypto, homomorphic encryption) are in Encryption at Rest, in Transit & in Use; password storage is in Password Hashing & Signed Tokens and Authentication; service-to-service identity is in Mutual TLS & Securing Service-to-Service Traffic. The threat model that decides what to encrypt comes from Security Foundations. This page owns the decisions, the numbers, the key and certificate lifecycles, and the code that ties them together.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why systems need more than "use HTTPS"Why it exists
From Diffie-Hellman to 47-day certificatesWhere it comes from
Symmetric vs asymmetric, and why every system uses bothSymmetric vs asymmetric
Which algorithm for which jobChoosing primitives
ECB, CBC without a MAC, PKCS#1 v1.5, MD5, SHA-1, custom cryptoWhat to avoid
2^32 messages per key, XChaCha20, AES-GCM-SIVNonces and IVs at scale
DEK, KEK, KMS, GenerateDataKeyEnvelope encryption
Key versions, rotation, rewrap, min decryption versionKey hierarchy and rotation
Deleting data by deleting a keyCrypto-shredding
Generation, storage, HSM, destruction, FIPS 140-3Key management lifecycle
Disk, TDE, field-level, searchable encryptionEncryption at rest
TLS everywhere, TLS 1.3, cipher suite policy, terminationEncryption in transit
Internal mTLS and certificate pinningmTLS and pinning
CA, intermediate, chain, CSR, SANPKI
398, 200, 100, 47 days; CRL, OCSP, stapling; CTValidity and revocation
ACME, Let's Encrypt, step-ca, Vault PKI, cert-manager, SPIFFEACME and private PKI
Vault, Secrets Manager, Parameter Store, Secret ManagerSecrets management
Dynamic secrets, leases, rotationDynamic secrets
Env vs file vs sidecar vs API, sealed-secrets, ESO, SOPSSecret injection
gitleaks, trufflehogSecret sprawl
Sigstore, cosign, SLSASigning artefacts
crypto/rand, random_bytesRandomness
"We are FIPS compliant" and other claimsCompliance claims
Knobs and error messagesMechanics
CodeGo, Laravel
Leaked key, expired certificate, APP_KEY rotation, erasureSolving the classic problems
What to pick for which dataChoosing
Monolith to distributed systemIn architecture
Runnable numbers and expected outputsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Primitive by job.

JobUseAvoidGoPHP / Laravel
Encrypt data (AEAD)AES-256-GCM; ChaCha20-Poly1305 where there is no AES hardware; XChaCha20-Poly1305 for random nonces at volumeECB, CBC without a MAC, AES-CTR alonecrypto/cipher.NewGCM, x/crypto/chacha20poly1305openssl_encrypt('aes-256-gcm'), sodium_crypto_aead_xchacha20poly1305_ietf_encrypt, Crypt
Agree on a keyX25519 (ECDH); X25519MLKEM768 hybrid in TLSStatic RSA key transportcrypto/ecdhsodium_crypto_kx_*
SignEd25519; ECDSA P-256 where FIPS or WebPKI need it; RSA-PSS for RSARSA PKCS#1 v1.5 for new designs, DSAcrypto/ed25519, crypto/ecdsasodium_crypto_sign_*, openssl_sign
Encrypt to a public keyRSA-OAEP, or ECDH + AEAD (HPKE, age)RSA PKCS#1 v1.5 encryptionrsa.EncryptOAEPopenssl_public_encrypt(..., OPENSSL_PKCS1_OAEP_PADDING)
Derive keysHKDF-SHA-256Raw SHA-256 of a key, reusing one key for two purposescrypto/hkdfhash_hkdf('sha256', ...)
Integrity with a shared keyHMAC-SHA-256sha256(key + message), MD5, SHA-1crypto/hmachash_hmac('sha256', ...), signed URLs
Store passwordsArgon2id (bcrypt acceptable)Any fast hash, any encryptionx/crypto/argon2Hash::make with the argon2id driver
Random keys, nonces, tokensOS CSPRNGmath/rand, mt_rand, uniqid, time-based seedscrypto/rand.Read, rand.Textrandom_bytes, Str::random

Where plaintext exists, by layer.

LayerWho still sees plaintextStopsDoes not stop
TLS in transitEach TLS endpoint: load balancer, proxy, serviceNetwork sniffing, Wi-Fi, ISP, a compromised switchAnything after the terminating proxy
Disk / volume encryptionEvery process on the running hostA stolen or decommissioned disk, a snapshot leaked to another accountRoot, the database, the application
Database TDEAnyone who can log in to the databaseCopied data files and backupsSQL injection, a DBA, a replica reader
Field-level / application encryptionOnly code holding the key (via KMS)Database dumps, injection, analysts, logs of SQLA compromised application process
End-to-endOnly the endpoints (users' devices)The server operatorA compromised endpoint

Lifetimes to remember.

ThingNumberSource
Random 96-bit GCM nonces under one keyat most 2^32 encryptionsNIST SP 800-38D, section 8.3
Public TLS leaf certificate, from 2026-03-15200 days maxCA/Browser Forum Baseline Requirements
... from 2027-03-15 / 2029-03-15100 days / 47 daysBallot SC-081 schedule in the BRs
Let's Encrypt default / short-lived profile90 days / six daysLet's Encrypt announcement (January 2025)
AWS KMS automatic rotation default365 daysAWS KMS developer guide
Symmetric data-encryption key originator usageup to two yearsNIST SP 800-57 Part 1 Rev. 5
Short-lived subscriber certificate (no revocation required)7 days from 2026-03-15 (10 before)CA/Browser Forum Baseline Requirements

The design rules in one list.

RuleWhy
Never write crypto, compose it from a maintained libraryOWASP: "Custom Algorithms: Don't do this."
One key, one purpose; derive subkeys with HKDFA key reused across purposes breaks the proofs of both
Data keys are many and short-lived; master keys are few and never leave an HSMThat is envelope encryption
Every ciphertext carries a key id and versionRotation without archaeology
Every certificate renewal is automated and monitored47-day certificates make manual renewal an outage plan
Secrets come from a store at run time, not from git, images or build argsGit history is forever
Prefer credentials that expire on their own (leases, short-lived certificates)Revocation is the least reliable part of every system
Application1. DEK = 32 random bytes2. AES-256-GCM(DEK, nonce,record, aad = table/row/tenant)KMS / HSMAWS KMS, Cloud KMS, Key Vault,Vault TransitKEK tenant-7versions v1, v2 (primary)Wrap(DEK, context) or GenerateDataKeywrapped DEK (+ plaintext DEK on generate)rotate adds v3; rewrap changes only the wrapped DEKStored row (one column or several)wrapped DEKsafe to storeKEK id + versiontenant-7, v2nonce96 bitsciphertext + 16-byte tagdestroy KEK = crypto-shred every row

The picture is the heart of the page: the application encrypts with a data key it throws away, and only a wrapped copy of that key, the id and version of the key that wrapped it, the nonce and the ciphertext are stored. Everything else on this page is either about that master key (where it lives, how it rotates, how it dies) or about the channels and credentials around it.

Why it exists ​

"We use HTTPS" protects one hop of one request. Real systems also keep data on disks, in backups, in replicas, in caches, in message brokers and in logs; they hand credentials to hundreds of processes; and they trust certificates that expire. Every one of those is a place where plaintext or a key can leak. Cryptography in practice is the discipline of deciding, for each place, who should be able to read the data, and then making that true with keys that can be rotated and destroyed.

Without a designWith a design
One AES key in an environment variable encrypts everythingPer-record data keys wrapped by per-tenant KEKs in a KMS
Rotation means "decrypt everything, re-encrypt everything, hope"Rotation adds a key version; rewrap touches only wrapped keys
Deleting a customer means finding them in every backupDestroying their KEK makes every copy unreadable
Certificates renewed by a calendar reminderACME or a private CA renews them automatically, alerts on failure
Database passwords shared by every service for yearsDynamic credentials per instance, expiring in an hour
Secrets in .env files, CI variables, Slack and git historyOne store, audited reads, injected at run time, scanned for leaks

The analogy we reuse on this page: a bank with safe-deposit boxes. Each box has its own small key (the DEK). The bank never hands out a master key; instead, each box key is kept in a sealed envelope that only the vault room can open (the KEK inside the KMS). To open a box you bring the sealed envelope to the vault room, which opens it for you and logs the visit. Changing the vault-room lock (rotation) does not change any box; re-sealing envelopes with the new lock (rewrap) does not open any box. Burning one customer's envelopes (crypto-shredding) makes their boxes unopenable even if someone photocopied the boxes years ago. The staff ID badges at the door are certificates, the badge office is the CA, and the visitor log is Certificate Transparency.

Three common misunderstandings, up front ​

  1. "Our database is encrypted at rest, so the data is protected." Disk encryption and TDE stop someone who steals the disk or the backup file. They do nothing against SQL injection, a stolen database password or an over-privileged analyst, because the database decrypts for anyone who can log in. Decide the threat first, then the layer.
  2. "Asymmetric encryption is stronger, so use RSA for data." Public-key operations are slow and limited in size; every real protocol (TLS, age, HPKE, PGP) uses public keys only to agree on or wrap a symmetric key, then encrypts the data with an AEAD. Asymmetric is for key exchange and signatures; symmetric is for data.
  3. "Rotating the key protects data that already leaked." Rotation limits how much data one key protects and how long a stolen key stays useful for new data. Ciphertext an attacker already copied stays decryptable with the old key. Only destroying the key (and having no plaintext copies) removes access to old data.

Where it comes from ​

Public keys and certificates (1976 to 2008). Diffie and Hellman published key agreement in 1976 and RSA followed in 1977; X.509 certificates appeared with the ITU-T directory standards, and the IETF profile used on the Internet today is RFC 5280 (May 2008), which defines certificate paths, extensions such as subjectAltName, and CRLs. OCSP, the online status check, is RFC 6960 (June 2013).

Authenticated encryption (2001 to 2019). AES was standardised in FIPS 197 (2001). NIST SP 800-38D (November 2007) defined GCM and its IV rules, including the limit this page keeps quoting: "The total number of invocations of the authenticated encryption function shall not exceed 2^32 ... with the given key" for random IVs. ChaCha20-Poly1305 became RFC 8439 (June 2018); AES-GCM-SIV, the nonce-misuse-resistant AEAD, became RFC 8452 (April 2019). HKDF is RFC 5869 (May 2010); X25519 is RFC 7748 (January 2016); Ed25519 is RFC 8032 (January 2017); Argon2 is RFC 9106 (September 2021).

TLS 1.3 and the automated web PKI (2013 to 2025). Certificate Transparency (RFC 6962, June 2013) made every public certificate visible in "publicly auditable, append-only, untrusted logs". Let's Encrypt and ACME (RFC 8555, March 2019) made certificates free and automatic. TLS 1.3 (RFC 8446, August 2018) removed static RSA, CBC and every non-AEAD cipher suite. In December 2024 Let's Encrypt announced the end of OCSP ("primarily because it represents a considerable risk to privacy on the Internet"); its responders were turned off on 6 August 2025. It has since made six-day certificates generally available.

Shorter everything (2025 onward). CA/Browser Forum Ballot SC-081 (April 2025) set the schedule now written into the Baseline Requirements: maximum public TLS validity 200 days from 15 March 2026, 100 days from 15 March 2027, 47 days from 15 March 2029, with domain-validation reuse falling to 10 days. Its rationale: "Certificate status services, such as CRLs and OCSP, are technologies which do not adequately protect relying parties at the current scale of the internet". The same push shows up in secrets (Vault leases, dynamic credentials), in workload identity (SPIFFE SVIDs that live for an hour) and in software supply chains (Sigstore's ten-minute signing certificates).

text
     Year  Event                                          What changed for system design
1    1976  Diffie-Hellman key agreement                   Two parties agree on a key over an open channel
2    2001  FIPS 197 (AES)                                 One standard block cipher, hardware support follows
3    2007  NIST SP 800-38D (GCM)                          AEAD in one pass; the 2^32 random-IV limit
4    2008  RFC 5280                                       The X.509 profile, chains, SAN, CRLs
5    2013  RFC 6962 Certificate Transparency, RFC 6960    Misissuance becomes visible; OCSP standardised
6    2016  RFC 7748 (X25519), Let's Encrypt GA            Fast key agreement; free automated certificates
7    2018  RFC 8446 TLS 1.3, RFC 8439 ChaCha20-Poly1305   AEAD-only, forward secrecy always, 1-RTT handshake
8    2019  RFC 8555 ACME, RFC 8452 AES-GCM-SIV, FIPS 140-3 Automated issuance; misuse resistance; new validation
9    2025  Go 1.24 X25519MLKEM768 default                 Hybrid post-quantum key exchange by default
10   2025  LE ends OCSP; SC-081 adopted                   Revocation gives way to short lifetimes
11   2029  47-day maximum public TLS certificate          Manual renewal is no longer an option

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, how products differ, and the fix.

Symmetric vs asymmetric encryption Must-know ​

In plain words: symmetric encryption uses one shared secret key to lock and unlock; asymmetric encryption uses a key pair, a public key anyone may have and a private key only the owner has. Systems use asymmetric keys to meet and prove identity, and symmetric keys to move and store data.

Common misunderstanding: "TLS encrypts my traffic with the server's RSA key." In TLS 1.3 the certificate key only signs the handshake; both sides derive symmetric traffic keys from an ephemeral (EC)DHE exchange (X25519 or a hybrid such as X25519MLKEM768) and encrypt with AES-GCM or ChaCha20-Poly1305.

Definition: symmetric (secret-key) algorithms such as AES use the same key for encryption and decryption and are fast (gigabytes per second with AES-NI). Asymmetric (public-key) algorithms such as RSA, ECDH over Curve25519 or P-256, and Ed25519 use a key pair; they provide key agreement, public-key encryption of small values and digital signatures, and are orders of magnitude slower. A hybrid scheme uses the asymmetric part to establish or wrap a symmetric key and the symmetric part for the bulk data.

text
     Step  Client                                   Server
1          ClientHello: key share (X25519 public)   
2                                                   ServerHello: key share; both compute the shared secret
3                                                   Certificate + CertificateVerify (signature, asymmetric)
4          verify chain and signature               
5          HKDF derives traffic keys                HKDF derives traffic keys
6          application data: AES-GCM (symmetric) ->

Real scenarios: HTTPS (ECDHE then AEAD); age and SOPS encrypting a file to several recipients' public keys by wrapping one file key; JWT signing with Ed25519 or ES256 so many services can verify with the public key while one issuer holds the private key; webhooks signed with HMAC because sender and receiver share a secret; envelope encryption where even the "master" key is symmetric (KMS KEKs are AES-256 keys inside an HSM).

PropertySymmetric (AES-GCM, ChaCha20-Poly1305, HMAC)Asymmetric (X25519, Ed25519, ECDSA, RSA)
KeysOne shared secretPublic + private pair
SpeedVery fast, hardware acceleratedSlow; RSA-2048 signing is thousands per second per core
Data sizeAnySmall (an RSA-2048 OAEP block holds 190 bytes with SHA-256)
Key distribution problemHard: both sides need the secretEasy: publish the public key, certify it
Typical useBulk data, storage, MACsKey agreement, signatures, identity, wrapping keys
Non-repudiationNo (both can produce the MAC)Yes for signatures (only the private key holder)

Fix / how to use it: design every protocol as "asymmetric to agree or authenticate, symmetric AEAD for data", and use a construction that already does this (TLS, HPKE, age, crypto_box) instead of combining RSA and AES by hand.

Choosing primitives by use case Must-know ​

In plain words: there is a short list of boring, well-studied choices, one per job. Pick from it and spend your design time on keys, not algorithms.

Common misunderstanding: "AES-256 is the strongest, so AES-256-CBC is the right choice." The mode matters more than the key size. CBC gives confidentiality only; without a MAC an attacker can modify ciphertext and, with a padding oracle, decrypt it. An AEAD (AES-GCM, ChaCha20-Poly1305) authenticates the ciphertext and the associated data in one step.

Definition: an AEAD (Authenticated Encryption with Associated Data) takes a key, a nonce, the plaintext and associated data (AAD, authenticated but not encrypted), and returns ciphertext plus a tag; decryption fails if any bit of ciphertext, nonce, tag or AAD changed. The recommended set: AES-256-GCM (NIST, FIPS, hardware everywhere) or ChaCha20-Poly1305 (RFC 8439, fast in software, constant time without AES-NI) for data; X25519 ECDH for key agreement; Ed25519 for signatures, ECDSA P-256 when FIPS or a WebPKI CA requires it, RSA-PSS when RSA is required; RSA-OAEP for public-key encryption when RSA is unavoidable; HKDF to derive keys from a secret; HMAC-SHA-256 for integrity with a shared key; Argon2id for passwords (owned by Password Hashing).

text
     Need                                   Decision path
1    "store this field encrypted"           AEAD -> AES-256-GCM, fresh DEK per value, AAD = table/column/row
2    "two services share a key"             do not; use mTLS or a KMS; if you must, HKDF from one root per purpose
3    "prove this file came from us"         signature -> Ed25519 (or ECDSA P-256 under FIPS); Sigstore for artefacts
4    "receiver verifies we sent this hook"  shared secret -> HMAC-SHA-256 over timestamp + body, constant-time compare
5    "derive per-tenant keys"               HKDF-SHA-256(root, salt, info = "tenant/42/pii/v1")

Real scenarios: a payments team needs FIPS 140-3 validated modules, so it picks AES-256-GCM and ECDSA P-256 over ChaCha20 and Ed25519; a mobile SDK on low-end ARM picks ChaCha20-Poly1305; a webhook platform signs payloads with HMAC-SHA-256 and a timestamp; a license server signs license files with Ed25519 so the client can verify offline.

Product / libraryDefault data cipherSignaturesNotes
Go stdlibAES-GCM via cipher.NewGCM; ChaCha20 in x/cryptoEd25519, ECDSA, RSA-PSScrypto/hkdf since Go 1.24
libsodium / PHP sodiumXChaCha20-Poly1305 (secretbox is XSalsa20)Ed25519Misuse-resistant APIs, no algorithm choices to get wrong
Laravel CryptAES-256-CBC + HMAC-SHA-256 (encrypt-then-MAC)n/aaes-256-gcm supported via app.cipher
AWS KMSAES-256-GCM (symmetric keys)RSA-PSS, ECDSA keysKEKs live in FIPS 140-3 Level 3 HSMs
HashiCorp Vault Transitaes256-gcm96 defaulted25519, ecdsa-p256, rsa-*Convergent mode available for deterministic encryption
Google TinkAES-GCM, AES-GCM-SIV, XChaCha20Ed25519, ECDSAKey sets with ids and rotation built in

Fix / how to use it: encode the table above as a short internal standard ("crypto policy") and expose one wrapper per job in your codebase. The Go envelope package and the Laravel EnvelopeEncrypter are examples.

What to avoid Must-know ​

In plain words: most real cryptographic failures come from a short list of known-bad choices that still appear in tutorials and old code.

Common misunderstanding: "MD5 is broken for passwords but fine for integrity." MD5 and SHA-1 both have practical collisions (SHA-1's SHAttered collision was published in 2017); an attacker can craft two different files with the same hash. They are acceptable only for non-security checksums. The CA/Browser Forum schedules the sunset of "all remaining use of SHA-1 in Certificates and CRLs" on 15 September 2026.

Definition:

AvoidWhyInstead
ECB modeEncrypts equal blocks to equal ciphertext: patterns survive (the famous penguin picture)Any AEAD
CBC (or CTR) without a MACMalleable; CBC with error-revealing decryption is a padding oracle (Vaudenay 2002) that decrypts byte by byteAEAD, or encrypt-then-MAC as Laravel does
RSA PKCS#1 v1.5 encryptionBleichenbacher's adaptive chosen-ciphertext attack (1998) and its ROBOT revivalRSA-OAEP, or ECDH + AEAD
Raw RSA, RSA without paddingDeterministic and malleableOAEP for encryption, PSS for signatures
MD5, SHA-1 for any security purposePractical collisionsSHA-256, SHA-3, BLAKE2/3
hash(key + message) as a MACLength-extension attacks on SHA-256HMAC-SHA-256
Fast hashes for passwordsGPUs test billions per secondArgon2id, bcrypt, scrypt
Custom ciphers, home-made protocolsUnreviewed; OWASP: "Custom Algorithms: Don't do this."TLS, HPKE, age, libsodium, Tink
Static IVs, counters reset on restartNonce reuse destroys GCMRandom nonces within limits, XChaCha20, SIV
== to compare MACs or tokensTiming side channelhmac.Equal, hash_equals
text
     Padding oracle in four lines (CBC without a MAC)
1    attacker flips a byte of ciphertext block C[i-1] and sends it
2    server decrypts, padding check fails -> "400 bad padding"; or passes -> "500 bad data"
3    the difference reveals one byte of plaintext of block C[i]; repeat 256 x 16 times per block
4    no key needed; the server's error message is the decryption oracle

Real scenarios: an old Java service using AES/ECB/PKCS5Padding because it was the default transformation; a cookie encrypted with CBC and no MAC, decrypted by a padding oracle; an integration partner that still sends RSA PKCS#1 v1.5 encrypted fields; an "integrity" column with MD5 of a card number (also a privacy leak: the card space is small enough to brute-force).

Fix / how to use it: add these to code review and to a static check (gosec flags weak primitives; semgrep has rules for md5(, ECB and mt_rand), and migrate old ciphertext by decrypting with the legacy path and re-encrypting with the AEAD path on read or in a backfill job.

Nonces and IVs at scale Must-know ​

In plain words: an AEAD needs a number used once (a nonce, or IV) per encryption under the same key. If it is ever reused with the same key, AES-GCM and ChaCha20-Poly1305 leak the XOR of the two plaintexts and let an attacker forge messages.

Common misunderstanding: "Random 96-bit nonces never collide, so I can encrypt forever with one key." The birthday bound makes collisions likely long before 2^96. NIST SP 800-38D caps random-IV GCM at 2^32 encryptions per key, and our lab program shows a 39% collision probability at 2^48 messages.

Definition: GCM uses a 96-bit IV. SP 800-38D allows two constructions: deterministic (a fixed field plus an invocation counter, unique per device) or RBG-based (random). For the random construction, "the total number of invocations of the authenticated encryption function shall not exceed 2^32 ... with the given key". RFC 8439: if a ChaCha20-Poly1305 nonce repeats, "both the one-time Poly1305 key and the keystream are identical between the messages", which "reveals the XOR of the plaintexts". Three ways out: a fresh key per message (envelope encryption with a DEK per record, so each key encrypts once); a longer nonce (XChaCha20-Poly1305, 192-bit nonce, draft-irtf-cfrg-xchacha); or a nonce-misuse-resistant AEAD (AES-GCM-SIV, RFC 8452), where "encrypting two messages with the same nonce only discloses whether the messages were equal or not".

text
     Messages under one key   P(collision), random 96-bit   P(collision), random 192-bit (XChaCha20)
1    2^20 (1 million)         6.94e-18                      8.76e-47
2    2^32 (NIST limit)        1.16e-10                      1.47e-39
3    2^40                     7.63e-06                      9.63e-35
4    2^48                     0.393                         6.31e-30
     (computed by cmd/noncemath in this chapter's Go module)

Real scenarios: a log pipeline encrypting 10,000 events per second under one key reaches 2^32 in about five days (119.3 hours); a fleet of devices that each start their GCM counter at zero after a firmware reset; a Kafka producer that encrypts message payloads with one static key; a database column encrypted with one AES-GCM key for billions of rows.

ApproachNonce ruleLimit per keyProducts
AES-GCM, random 96-bit IVRandom from a CSPRNG2^32 encryptions (SP 800-38D)Go NewGCM, OpenSSL, AWS KMS internally
AES-GCM, deterministic counterUnique fixed field per device + counter2^32 per fixed field, counter must survive restartsTLS record layer (sequence number XOR IV)
ChaCha20-Poly130596-bit, never repeatSame birthday reasoning as GCMRFC 8439, WireGuard (counter), TLS 1.3
XChaCha20-Poly1305192-bit randomRandom nonces practically unlimitedlibsodium, x/crypto/chacha20poly1305.NewX, age payload uses ChaCha20-Poly1305 with derived keys
AES-GCM-SIVRepeats leak only equalityMisuse-resistant, not misuse-freeTink, BoringSSL, RFC 8452
Envelope, DEK per recordAny random nonce, one message per keyBounded by KMS calls insteadAWS Encryption SDK, Vault Transit datakey, this chapter's Go code

Fix / how to use it: never manage nonces by hand for stored data; use a DEK per record or per object (and a random nonce), or XChaCha20-Poly1305 where you must encrypt many messages under one key, and count encryptions per key where a key is long-lived so you rotate before the limit.

Envelope encryption: DEK, KEK and a KMS Must-know ​

In plain words: encrypt the data with a fresh data key (DEK), then encrypt that data key with a master key (KEK) that lives in a key management service (KMS) and never comes out. Store the wrapped DEK next to the data.

Common misunderstanding: "Calling KMS Encrypt on every field is the same thing." AWS KMS Encrypt accepts at most 4096 bytes and Google Cloud KMS at most 64 KiB, every call is a network round trip with a per-request price and a rate quota, and the data travels to the KMS. Envelope encryption sends only 32-byte keys to the KMS and keeps bulk data local.

Definition: AWS: "Envelope encryption is the practice of encrypting plaintext data with a data key, and then encrypting the data key under another key"; eventually "one key must remain in plaintext so you can decrypt the keys and your data. This top-level plaintext key encryption key is known as the root key", and in AWS KMS root keys "never leave the AWS KMS FIPS 140-3 Security Level 3 validated hardware security modules unencrypted". Google Cloud: "The DEK is encrypted (also known as wrapped) by a key encryption key (KEK)"; "Generate a new DEK every time you write the data. This means you don't need to rotate the DEKs"; "Do not use the same DEK to encrypt data from two different users"; and "The KEK never leaves Cloud KMS". AWS returns both copies from one call: GenerateDataKey gives "a plaintext copy of the data key and a copy that is encrypted under a symmetric encryption KMS key". Vault Transit offers the same through transit/datakey, and stores nothing: "Vault doesn't store the data sent to the secrets engine".

text
     Encrypt (one record)                                    Decrypt
1    app -> KMS: GenerateDataKey(KeyId, AES_256, context)    app reads row: wrapped DEK, kek id+version, nonce, ct
2    KMS -> app: plaintext DEK + wrapped DEK                 app -> KMS: Decrypt(wrapped DEK, context)
3    app: ct = AES-256-GCM(DEK, nonce, record, aad)          KMS checks IAM policy + context, logs to CloudTrail
4    app: forget plaintext DEK                               KMS -> app: plaintext DEK
5    store: wrapped DEK | kek id | version | nonce | ct      app: record = AES-256-GCM-Open(DEK, nonce, ct, aad)

Real scenarios: S3 SSE-KMS (a data key per object, or per bucket key with S3 Bucket Keys); EBS volumes (one data key per volume); a health-records table where each note gets its own DEK and the KEK is per hospital; Kubernetes etcd encryption with the KMS v2 provider (a locally generated DEK wrapped by a KMS key); a backup tool encrypting each archive with a fresh key wrapped for two regions.

ProductGenerate DEKUnwrapRewrapContext / AADNotes
AWS KMSGenerateDataKey, GenerateDataKeyWithoutPlaintextDecryptReEncrypt (server side)EncryptionContext, logged in CloudTrailAWS Encryption SDK adds data-key caching
Google Cloud KMSGenerate locally, Encrypt to wrapDecryptDecrypt + Encrypt with new primaryadditionalAuthenticatedData64 KiB max input; key ring / key / version hierarchy
Azure Key VaultGenerate locally, wrapKeyunwrapKeyunwrap + wrapn/a for RSA wrapRSA-OAEP or AES key wrap; Managed HSM for FIPS Level 3
HashiCorp Vault Transittransit/datakey/plaintext/:nametransit/decrypt/:nametransit/rewrap/:namecontext with derived keysCiphertext prefixed vault:v1: with the key version
Google Tink / AWS Encryption SDKLibrary-managedLibrary-managedLibrary-managedBuilt inMulti-KMS, multi-region keyrings

Fix / how to use it: never invent the storage format ad hoc: include a format version, the KEK id, the KEK version, the wrapped DEK, the nonce and the ciphertext, and bind the record's identity as AAD (or encryption context) so a ciphertext copied to another row fails. Cache plaintext DEKs only briefly and only for reads that repeat, as the AWS Encryption SDK's caching CMM does, to keep KMS cost and latency down.

Key hierarchy, rotation and re-wrap Must-know ​

In plain words: keys form a tree: a root key in an HSM protects KEKs, KEKs protect DEKs, DEKs protect data. Rotation creates a new version of a key for new data; rewrap moves wrapped keys to the new version without touching the data.

Common misunderstanding: "Key rotation means re-encrypting the whole database." With envelope encryption, rotating a KEK only changes what wraps the DEKs. AWS KMS automatic rotation does not even require rewrapping: KMS keeps every old key material version and picks the right one on Decrypt. Rewrap is needed when you want to retire an old version or move to a different key.

Definition: a key hierarchy is a tree of keys where each level encrypts the level below (Cloud KMS: key ring, key, key version; AWS KMS: KMS key with backing key material versions; Vault: named key with numbered versions). Rotation creates a new primary version used for all new encryptions; older versions remain for decryption. Rewrap (Vault transit/rewrap, AWS ReEncrypt) decrypts a wrapped key with the old version and encrypts it with the primary version inside the KMS, so "this process does not reveal the plaintext data", in Vault's words. A minimum decryption version (Vault min_decryption_version) then refuses old versions, after which they can be destroyed. AWS KMS rotation runs "every year" by default ("the default value is 365 days") and accepts a custom period.

text
     t        Action                                   Envelopes in DB                 KMS state
1    day 0    create KEK tenant-7 (v1)                 all new rows: v1                v1 primary
2    day 365  rotate                                   old rows v1, new rows v2        v1 decrypt-only, v2 primary
3    day 366  batch rewrap job (idempotent, chunked)   rows move v1 -> v2, data untouched  v1 still allowed
4    day 370  job reports 0 rows on v1                 all v2                          set min_decryption_version = 2
5    day 400  no errors for 30 days                    all v2                          destroy v1 (irreversible)

Real scenarios: an annual compliance requirement to rotate KEKs; a suspected leak of a KMS admin credential, answered by rotating and rewrapping within a day; migrating from a self-hosted Vault to AWS KMS by rewrapping every DEK from Vault to KMS; Laravel APP_KEY rotation, which is a single-level hierarchy and therefore needs a real re-encryption of every value (covered in Solving).

ProductRotationOld versionsRewrapRetire old versions
AWS KMSAutomatic (default 365 days, custom period) or on demandKept forever, transparent on DecryptReEncrypt to another keyNot per version; schedule key deletion (7 to 30 days)
Google Cloud KMSAutomatic rotation scheduleEnabled versions decryptDecrypt + EncryptDisable then destroy a version
Azure Key VaultRotation policyKept as versionsunwrap + wrapDisable a version
Vault Transittransit/keys/:name/rotate, auto_rotate_periodWorking settransit/rewrap/:namemin_decryption_version, then trim
Laravel APP_KEYManual: new APP_KEY, old into APP_PREVIOUS_KEYSTried in order on decryptRe-encrypt every valueRemove from APP_PREVIOUS_KEYS

Fix / how to use it: store the KEK id and version with every envelope (an indexed column), make rewrap an idempotent batch job that reports how many rows remain on old versions, and only raise the minimum decryption version after that count is zero. NIST SP 800-57 gives the planning numbers: a symmetric data-encryption key has an originator-usage period of up to two years.

Crypto-shredding Important ​

In plain words: instead of finding and deleting every copy of someone's data, encrypt their data under a key used only for them, and delete the key. Every copy, in every backup and replica, becomes unreadable at once.

Common misunderstanding: "Crypto-shredding deletes the data." The ciphertext is still there; it becomes useless only if the key is really gone everywhere (KMS backups, cached DEKs, exported key material) and no plaintext copy exists elsewhere (search indexes, analytics exports, logs). It is a strong technique, not a legal guarantee by itself.

Definition: crypto-shredding (crypto-erase) is deletion by key destruction. It needs a key granularity that matches the deletion unit (per user, per tenant, per dataset), envelope encryption so each unit's DEKs are wrapped by that unit's KEK, and a KMS that can destroy a key with an audit trail (AWS KMS scheduled key deletion, Cloud KMS version destroy, Vault key deletion with deletion_allowed).

text
     t      Event                                               Effect
1    t0     user 42's data encrypted under KEK user-42          DB rows, S3 objects, nightly backups all hold ciphertext
2    t1     erasure request (GDPR Art. 17)                      app deletes live rows; backups are immutable for 35 days
3    t1     schedule deletion of KEK user-42 (7-day window)     reads of user-42 data fail with "key pending deletion"
4    t1+7d  KEK destroyed                                       every copy, including backups restored in 2030, is noise

Real scenarios: right-to-erasure in an event-sourced system where events are immutable (encrypt personal fields per subject, shred the key); tenant offboarding in a SaaS product; deleting a dataset from immutable Kafka topics with long retention; decommissioning a region.

GranularityKeys to manageErasure unitFits
One KEK for everything1None (all or nothing)Not crypto-shredding
Per tenantTenants (hundreds to thousands)Tenant offboardingB2B SaaS
Per user / data subjectUsers (millions): use derived or wrapped per-user keys under a tenant KEKOne personGDPR erasure in event stores and logs
Per dataset or partitionDatasetsOne export or one month of dataAnalytics, retention windows

Fix / how to use it: for millions of subjects, do not create a KMS key per user (quotas and cost); keep per-user keys in a key table, each wrapped by a tenant KEK, and delete the row to shred the user. The Go test TestCryptoShreddingOneTenant shows the effect with the local fake KMS.

Key management lifecycle, HSM and FIPS 140-3 Important ​

In plain words: a key is born, used, rotated, retired and destroyed, and every step needs an owner, a place and a log. The safest place for long-lived keys is hardware that performs operations without ever exporting the key.

Common misunderstanding: "We use an HSM, so we are FIPS compliant." FIPS 140-3 validates a module at a security level for an approved mode of operation; your system is only "using FIPS 140-3 validated cryptography" if every relevant operation runs in such a module, in approved mode, with approved algorithms.

Definition: NIST SP 800-57 Part 1 Rev. 5 (May 2020) describes key states (pre-activation, active, suspended, deactivated, compromised, destroyed) and cryptoperiods, "the time span during which a specific key is authorized for use". NIST SP 800-130 (August 2013) is the framework for designing a Cryptographic Key Management System (CKMS); SP 800-175B Rev. 1 (March 2020) guides the use of the standards. An HSM (hardware security module) generates and stores keys and performs operations inside tamper-resistant hardware (AWS CloudHSM, Azure Managed HSM, Google Cloud HSM, Thales Luna, YubiHSM). FIPS 140-3 (March 2019) is the US/Canadian standard for validating cryptographic modules, with four security levels; the CMVP publishes validated modules.

text
     State          Example (KEK tenant-7)                         Who acts
1    generate       inside the KMS/HSM, never exported              KMS on CreateKey
2    active         wraps new DEKs, unwraps old ones                application role via IAM
3    rotated        new version primary; old version decrypt-only   KMS schedule
4    deactivated    min decryption version raised                   key custodian, after rewrap reports 0
5    destroyed      scheduled deletion elapsed                      key custodian, two-person approval

Real scenarios: PCI DSS key custodians with split knowledge for a payment HSM; Go services built with GOFIPS140=v1.0.0 for a FedRAMP workload; a bank requiring that its own HSM holds the root (AWS KMS External Key Store, Google Cloud EKM, bring-your-own-key); destroying an old KEK only after a rewrap job proves no envelope uses it.

OptionWho holds the rootFIPS 140-3Trade-off
AWS KMS / Cloud KMS / Key Vault (software or HSM tier)Cloud provider HSMsLevel 3 HSMs (AWS KMS states Level 3)Easiest; provider is in the trust boundary
Cloud HSM (AWS CloudHSM, Azure Managed HSM)You, in a dedicated HSMLevel 3You run clusters, backups, quorum
External key store (AWS XKS, Google EKM)Your on-premises HSMYour module's levelEvery decrypt depends on your HSM's availability
Vault with HSM auto-unseal (Enterprise) or KMS sealVault, rooted in an HSM or cloud KMSDepends on the sealPortable across clouds
Go Cryptographic Module (GOFIPS140)Your processCMVP validation of the moduleApproved algorithms only in FIPS mode

Fix / how to use it: write the lifecycle down per key class (who can create, use, rotate, disable and destroy, and which log shows it), use IAM to separate key administrators from key users, and state FIPS claims at the module and algorithm level (see Compliance claims).

Encryption at rest: disk, TDE, field-level and searchable Must-know ​

In plain words: "encrypted at rest" can mean four very different things, from "the disk is encrypted" to "only the application can read this column". The higher the layer, the more attackers it stops and the less the database can do with the data.

Common misunderstanding: "Field-level encryption is just stronger TDE." It changes what the database can do: no LIKE, no range queries, no sorting, no indexes on the plaintext. Laravel's own documentation warns that with encrypted casts "you will not be able to query or search encrypted attribute values".

Definition: volume or disk encryption (LUKS/dm-crypt, BitLocker, AWS EBS encryption, GCE persistent disk, Azure Disk Encryption) encrypts blocks below the filesystem. Transparent data encryption (TDE: SQL Server, Oracle, MySQL InnoDB data-at-rest encryption, MongoDB Enterprise, Percona's pg_tde for PostgreSQL) encrypts data files and backups inside the database engine; community PostgreSQL has no TDE and relies on disk encryption or pgcrypto. Field-level (application-level) encryption encrypts values before they reach the database. Searchable encryption is the family of techniques that keep some query ability: deterministic encryption (same plaintext gives same ciphertext: equality joins, but it leaks equality and frequency), blind indexes (a keyed HMAC of the normalized value in a separate column), and specialised schemes (MongoDB Queryable Encryption, order-revealing encryption) with documented leakage. The database-side details are owned by Encryption at Rest, in Transit & in Use.

Application / field-level (AES-GCM, envelope, KMS)Protects: SQL injection dumps, DBAs, replicas, backups, logsCosts: no LIKE/ORDER BY/range; blind index for exact matchDatabase TDE (SQL Server, Oracle, MySQL InnoDB, Percona pg_tde)Protects: data files and backups copied off the hostNot: anyone who can log in and run SELECTVolume / disk (LUKS, BitLocker, EBS, GCE PD, Azure Disk)Protects: stolen or decommissioned disks, snapshots in other accountsNot: a running server, root, the database itselfObject storage (S3 SSE-KMS, GCS CMEK)Protects: the provider's media; with KMS keys, adds an access checkNot: anyone holding IAM read on the bucket and decrypt on the keyThreat reachtop layer: plaintext onlyinside the app processmiddle: plaintext insidethe database enginebottom: plaintext for everyprocess on the hosthigher = more protection,less query power
text
     Attack                                     Disk   TDE   Field-level
1    stolen laptop / decommissioned disk        stops  stops stops
2    backup file copied to a personal bucket    no*    stops stops     (* unless the backup is also encrypted)
3    SQL injection: SELECT * FROM patients      no     no    stops (ciphertext returned)
4    analyst with read access to the replica    no     no    stops
5    compromised application server             no     no    no (it holds the key access)

Real scenarios: card data under PCI DSS (field-level, with a tokenisation vault); a patients table with a blind index on national id for exact lookups; an e-mail column encrypted deterministically to keep a unique constraint (accepting the equality leak); an analytics warehouse where disk encryption is enough because access control is the real boundary.

TechniqueQuery abilityLeaksProducts
Randomized AEAD (default)NoneLengthLaravel encrypted cast, Go AES-GCM, Tink
Deterministic (AES-SIV, Vault convergent)Equality, joins, uniqueEquality, frequencyVault Transit convergent_encryption, Tink Deterministic AEAD, MongoDB CSFLE deterministic
Blind index (HMAC)Exact match on a separate columnEquality of the indexed valueCipherSweet (PHP), hand-written HMAC column
Queryable / structured encryptionEquality, range (product-specific)Documented, product-specificMongoDB Queryable Encryption
TokenisationLookup through the vaultNothing in the app DBPayment processors, VGS, Basis Theory

Fix / how to use it: encrypt at the highest layer that the queries allow, add a blind index only for fields with high cardinality, keep blind-index keys separate from encryption keys (HKDF subkeys per column), and size columns as TEXT/bytea because ciphertext is longer than the plaintext.

sql
-- Envelope-encrypted notes with a KEK id column that drives rotation and shredding.
CREATE TABLE patient_notes (
    id            bigserial PRIMARY KEY,
    tenant_id     bigint      NOT NULL,
    body_envelope text        NOT NULL,          -- env1:... wrapped DEK + IV + tag + ciphertext
    kek_id        text        NOT NULL,          -- e.g. alias/tenant-7
    kek_version   integer     NOT NULL DEFAULT 1,
    created_at    timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX patient_notes_kek ON patient_notes (kek_id, kek_version);

-- Patients with a blind index for exact lookup by national id.
CREATE TABLE patients (
    id               bigserial PRIMARY KEY,
    national_id      text  NOT NULL,              -- randomized ciphertext
    national_id_bidx bytea NOT NULL UNIQUE        -- HMAC-SHA-256(column key, normalized value)[:16]
);

-- Rotation progress: how many envelopes still use an old KEK version?
SELECT kek_id, kek_version, count(*) AS rows_left
FROM patient_notes
GROUP BY kek_id, kek_version
ORDER BY kek_id, kek_version;

Encryption in transit: TLS everywhere, TLS 1.3, termination points Must-know ​

In plain words: every network hop carries TLS, including the ones inside your VPC. The policy says which versions and cipher suites are allowed, and the architecture says where TLS ends and starts again.

Common misunderstanding: "Traffic inside the VPC is private, so plaintext is fine behind the load balancer." Internal networks are where attackers move laterally after the first foothold; cloud providers also mirror traffic for debugging. Zero-trust designs encrypt and authenticate every hop.

Definition: TLS 1.3 (RFC 8446) defines five cipher suites, all AEAD; "A TLS-compliant application MUST implement the TLS_AES_128_GCM_SHA256 ... cipher suite and SHOULD implement the TLS_AES_256_GCM_SHA384 ... and TLS_CHACHA20_POLY1305_SHA256". Key exchange is always ephemeral, so every connection has forward secrecy. TLS 1.2 is still needed for old clients and must be limited to ECDHE + AEAD suites. A TLS termination point is where the encrypted connection ends and plaintext exists: at a CDN (Cloudflare, CloudFront), at a load balancer (AWS ALB, NGINX, HAProxy, Envoy), at a sidecar (Istio, Linkerd), or in the application. TLS passthrough (AWS NLB TCP, HAProxy mode tcp) leaves termination to the backend; re-encryption terminates and opens a new TLS connection to the backend. The load-balancing view is in Load Balancing; HTTP/2 and HTTP/3 implications are in HTTP Evolution.

text
     Hop                               Protocol                     Who sees plaintext
1    browser -> CDN edge               TLS 1.3, public certificate  CDN (Cloudflare / CloudFront)
2    CDN -> origin load balancer       TLS 1.2+, origin certificate CDN and ALB
3    ALB -> service sidecar            TLS (re-encrypt) or mTLS     ALB and the sidecar
4    sidecar -> service process        localhost plaintext          the pod only
5    service -> PostgreSQL             TLS, sslmode=verify-full     service and database

Real scenarios: an NGINX ingress with ssl_protocols TLSv1.2 TLSv1.3; PCI DSS requiring strong cryptography on every hop carrying card data; a gRPC mesh with automatic mTLS; a PostgreSQL client with sslmode=require that encrypts but does not verify the server (use verify-full); 0-RTT in TLS 1.3, which can be replayed (RFC 8446 lists "0-RTT and Anti-Replay" as its own section), so only idempotent requests may use it.

ProductProtocol knobCipher knobDefaults worth knowing
Go crypto/tlsMinVersion, MaxVersionCipherSuites (TLS 1.2 only)Minimum TLS 1.2, maximum 1.3; "TLS 1.3 ciphersuites are not configurable"; X25519MLKEM768 in the default curves since Go 1.24
NGINXssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers, ssl_conf_command Ciphersuitesssl_stapling on; for OCSP stapling
HAProxyssl-min-ver TLSv1.2ciphers, ciphersuitesssl-default-bind-options in global
AWS ALB / NLBSecurity policy nameSame (policy)Pick one of the ELBSecurityPolicy-TLS13-* policies
Envoytls_minimum_protocol_versioncipher_suitesSet both explicitly in DownstreamTlsContext
Server-Side TLS guidelines (TLSRef, formerly Mozilla)"Modern" (TLS 1.3 only), "Intermediate" (TLS 1.2 + 1.3, recommended)Intermediate 1.2 list: ECDHE + AES-GCM / ChaCha20 onlyThe usual starting point for NGINX, HAProxy, Apache

Fix / how to use it: adopt the "Intermediate" profile of the Server-Side TLS guidelines ("Recommended configuration for a general-purpose server") for public endpoints (TLS 1.2 and 1.3, ECDHE + AEAD only) and TLS 1.3 only where you control all clients; enable HSTS on HTTPS origins; verify certificates on every internal client (never InsecureSkipVerify or sslmode=require without verification); and draw every termination point on the architecture diagram.

Internal mTLS and certificate pinning Important ​

In plain words: in mutual TLS the client also presents a certificate, so the server knows which workload is calling. Pinning means a client accepts only a specific certificate or public key instead of any certificate from a trusted CA.

Common misunderstanding: "Pinning makes my mobile app more secure, so pin the leaf certificate." With 47-day certificates a pinned leaf breaks the app at every renewal; OWASP's current guidance concludes that "pinning creates much more risk than reward" and that "Trying to coordinate certificate rotations is a recipe for outages".

Definition: mTLS adds a CertificateRequest from the server and a client Certificate + CertificateVerify; the server validates the client chain against its client CA pool and authorises by identity (a SPIFFE ID in the URI SAN, or a DNS name). Certificate pinning fixes the expected leaf, intermediate or public key (SPKI hash) in the client. If pinning is warranted, OWASP says, "it should only be done when the client and server sides are both controlled by the same party", and you pin a key you control (your own intermediate or a backup key), never only the current leaf. The full service-to-service design is in Mutual TLS.

text
     Event                                   Pinned leaf              Pinned own intermediate + backup key
1    leaf renewed (every 47 days)            app rejects server       accepted
2    CA changes its intermediate             app rejects server       accepted (it is your own private CA)
3    attacker with a misissued public cert   rejected                 rejected
4    your intermediate key compromised       n/a                      switch to the backup pin, ship an update

Real scenarios: a payments service that accepts calls only from workloads with spiffe://prod.example/ns/checkout/sa/api; a banking app pinning its own private CA for an API that is never called by browsers; HTTP Public Key Pinning (HPKP) in browsers, which was abandoned after sites locked their own users out.

OptionProtects againstBreaks whenRecommendation
Standard WebPKI validation + CTMost misissuance (CT makes it visible)Never by itselfDefault
mTLS with a private CAUnauthenticated callers inside the networkCA rotation is not automatedDefault for service to service
Pin leaf certificateMisissued certificatesEvery renewalAvoid
Pin your own intermediate / SPKI with a backupMisissuance by public CAsYour CA rotation is not plannedOnly when you own both ends

Fix / how to use it: prefer mTLS with automatically rotated SVIDs over pinning; if a mobile client must pin, pin your own key set with at least one offline backup key and a remote kill switch.

PKI: certificate authorities, intermediates, chains, CSR and SAN Must-know ​

In plain words: a certificate is a signed statement "this public key belongs to this name, until this date". A certificate authority (CA) signs it; clients trust a small set of root CAs and follow a chain of intermediate certificates down to the leaf.

Common misunderstanding: "The Common Name is the hostname." Clients verify the subjectAltName (SAN) extension; Go ignores the Common Name entirely, and the Baseline Requirements require every name to appear in the SAN. A certificate valid for example.com and *.example.com fails for orders.internal.test with Go's error x509: certificate is valid for example.com, *.example.com, not orders.internal.test.

Definition: a PKI (public key infrastructure) is the set of CAs, policies, certificates, revocation services and trust stores (RFC 5280). A root CA is self-signed and distributed in trust stores (Mozilla NSS, Apple, Microsoft, Chrome Root Store); it stays offline and signs intermediate CAs, which sign leaf (end-entity) certificates. A certificate chain is the path leaf, intermediate(s), root; the server sends leaf plus intermediates, the client supplies the root. A CSR (certificate signing request, PKCS#10) carries the public key and requested names, signed with the private key to prove possession. Key extensions: subjectAltName (DNS, IP, URI names), basicConstraints (CA or not), keyUsage and extendedKeyUsage (serverAuth, clientAuth), name constraints for private intermediates.

Root CA (offline, HSM)self-signed, in trust storessigns intermediates onlyIntermediate CA (online)issues leaves; can be revokedwithout touching the rootLeaf: api.example.comSAN = DNS names, 6 to 200 daysEKU serverAuth, own key pairCT logsappend-only, publicprecert in, SCT outACME clientCSR + http-01 / dns-01 /tls-alpn-01 challengeRevocationCRL, OCSP, OCSP stapling,or just short lifetimesClient (browser, Go, curl)path: leaf, intermediate, rootchecks SAN, dates, statusSCTsserver sends leaf + intermediate chain
text
     Step  Actor            Action
1          server           generate key pair (ECDSA P-256), never leaves the host
2          server           CSR: public key + SAN api.example.com, signed with the private key
3          CA (ACME)        validate control of api.example.com (http-01 / dns-01 / tls-alpn-01)
4          CA               submit precertificate to CT logs, receive SCTs, sign the leaf
5          server           install leaf + intermediate (fullchain.pem)
6          client           build path to a trusted root, check SAN, validity period, EKU, revocation

Real scenarios: a missing intermediate in fullchain.pem, which works in Chrome (it fetches the intermediate via AIA) and fails in Go and curl with x509: certificate signed by unknown authority; a wildcard certificate shared by fifty services so one leaked key compromises all of them; a private intermediate with name constraints limited to .internal.example; an expired root removed from old Android trust stores.

ConceptPublic WebPKIPrivate PKI
RootIn browser/OS trust stores, audited (WebTrust, ETSI)Distributed by you (MDM, config management, trust bundles)
Issuance validationDomain control (ACME challenges), OV/EV checksWhatever your policy says: workload attestation, IAM, SSO
Lifetimes200 days now, 47 days by 2029Hours to days for workloads
RevocationCRLs (OCSP being retired by Let's Encrypt)Often none: short lifetimes instead
TransparencyCT logs mandatory for browser trustOptional
NamesPublic DNS names, public IPsInternal names, SPIFFE IDs

Fix / how to use it: generate the key where it is used, never copy private keys between hosts, always serve the full chain, issue one certificate per service (not one wildcard for everything), and monitor expiry from the outside (blackbox exporter, uptime checks) in addition to the renewal job.

Validity periods, revocation and Certificate Transparency Must-know ​

In plain words: certificates are getting shorter because revocation does not work well. If a certificate lives a few days, stealing its key is worth little, and nobody needs to ask the CA "is this still valid?".

Common misunderstanding: "If our key leaks, we revoke the certificate and we are safe." Browsers largely do not perform live revocation checks, OCSP soft-fails when the responder is unreachable, and Let's Encrypt no longer runs OCSP at all. The CA/Browser Forum's own ballot says status services "do not adequately protect relying parties at the current scale of the internet".

Definition: the validity period is notBefore to notAfter. Baseline Requirements schedule: 398 days until 15 March 2026; then "Maximum validity period of Subscriber Certificates is 200 days"; from 15 March 2027, 100 days; from 15 March 2029, 47 days. A short-lived subscriber certificate (7 days or less from 15 March 2026, 10 before) need not support revocation. Revocation mechanisms: CRL (a signed list of revoked serials), OCSP (RFC 6960, an online per-certificate query that leaks browsing to the CA), OCSP stapling (the server attaches a fresh OCSP response in the handshake), OCSP Must-Staple (a certificate extension, now rejected by Let's Encrypt), browser-pushed sets (CRLite, CRLSets). Certificate Transparency (RFC 6962): CAs submit precertificates to public append-only logs and embed signed certificate timestamps (SCTs); "TLS clients MUST reject certificates that do not have a valid SCT" in the RFC's model, and Chrome and Safari enforce CT for public certificates. Domain owners monitor CT logs (crt.sh, Cert Spotter) to detect certificates they did not request.

text
     Date        Rule (CA/Browser Forum BRs, Let's Encrypt)
1    2024-12     Let's Encrypt announces the end of OCSP
2    2025-05-07  LE drops OCSP URLs from certificates, Must-Staple requests fail
3    2025-08-06  LE turns off OCSP responders
4    2026-03-15  max public TLS validity 200 days; DCV reuse 200 days; short-lived = 7 days
5    2026-09-15  sunset of remaining SHA-1 in certificates and CRLs
6    2027-03-15  max validity 100 days
7    2029-03-15  max validity 47 days; DCV reuse 10 days

Real scenarios: an outage because a manually renewed certificate on an internal load balancer expired (the classic); a VPN appliance that hard-fails when a certificate has no OCSP URL (Let's Encrypt warned about this); a CT monitor alerting that a certificate for login.example.com was issued by a CA you never use (phishing or misissuance); a renewal that uploads a new certificate to one of three load balancers.

MechanismHow the client learnsPrivacyReliabilityStatus
CRLDownloads the CA's listGoodLarge lists, stale between updatesLet's Encrypt's only mechanism since 2025
OCSPAsks the CA per certificatePoor (CA sees what you visit)Soft-fail when unreachableBeing retired by Let's Encrypt
OCSP staplingServer staples a signed responseGoodServer bugs can cause downtimeNGINX ssl_stapling on
Short-lived certificatesCertificate expires before revocation mattersGoodRequires automationLet's Encrypt six-day profile, SPIFFE SVIDs
CT + monitoringNot a client check: owner detects misissuancePublic by designHighMandatory for public certificates

Fix / how to use it: treat certificate lifetime as a design parameter: automate renewal at one third of the remaining lifetime, alert at one half, test renewal paths continuously, monitor CT for your domains, and add CAA DNS records to restrict which CAs may issue for you.

ACME automation and private PKI: step-ca, Vault PKI, cert-manager, SPIFFE/SPIRE Must-know ​

In plain words: ACME is the protocol that lets a machine ask a CA for a certificate, prove it controls the name, and renew it without humans. Inside your network, a private CA issues certificates the same way for internal names and workload identities.

Common misunderstanding: "Internal services can use one long-lived self-signed certificate." That certificate has no rotation path, no revocation and no identity per workload; when it expires, everything fails at once. A private CA with short-lived certificates is cheaper to run than the outage.

Definition: ACME (RFC 8555, March 2019) defines accounts, orders, authorizations and challenges: http-01 (a file under /.well-known/acme-challenge/), dns-01 (a TXT record, required for wildcards) and tls-alpn-01 (RFC 8737, a special certificate on port 443). Let's Encrypt is the largest ACME CA (90-day default, six-day profile). Private PKI options: smallstep step-ca (an online CA with ACME, OIDC and cloud-identity provisioners; it lets you "choose key types (RSA, ECDSA and EdDSA) and lifetimes"); HashiCorp Vault PKI (an API-driven intermediate; "By keeping TTLs relatively short, revocations are less likely to be needed", and it allows "ephemeral certificates" that are not stored); cert-manager on Kubernetes (Certificate, Issuer/ClusterIssuer resources, renewal into a Secret); SPIFFE (a standard for workload identity, spiffe://trust-domain/path IDs) and SPIRE (its reference implementation, which attests workloads and issues X.509-SVIDs and JWT-SVIDs through the Workload API, together with trust bundles for federation).

text
     Step  cert-manager + Let's Encrypt (public)           SPIRE (internal workload)
1          Certificate resource requests api.example.com    pod starts; SPIRE agent attests it (k8s SA, node)
2          ACME order, dns-01 TXT via Route 53              agent asks SPIRE server for an X.509-SVID
3          CA validates, issues 90-day cert                 SVID: URI SAN spiffe://prod.example/ns/pay/sa/api, 1 h TTL
4          cert-manager stores it in a Secret               Workload API streams SVID + trust bundle to the app/Envoy
5          renews at 2/3 of lifetime                        rotates before expiry, no restart

Real scenarios: Kubernetes ingress certificates through cert-manager with a ClusterIssuer for Let's Encrypt; database client certificates issued by Vault PKI with a 24-hour TTL to each CI job; Istio's built-in CA issuing SPIFFE-format certificates to every sidecar; a fleet of IoT devices enrolled through step-ca with an attestation provisioner.

ProductProtocolsTypical lifetimeStrengthWatch out
Let's EncryptACME90 days, or six daysFree, public trust, CTRate limits; public names only (and IPs with six-day certs)
cert-managerACME, Vault, Venafi, CA issuersFrom the issuerKubernetes-native renewalSecrets in etcd: encrypt etcd
smallstep step-caACME, OIDC, JWK, cloud IIDs, SCEPHours to daysSelf-hosted, ACME for internal namesYou run the CA's availability
Vault PKIHTTP API, ACME (Vault 1.14+)Minutes to daysTied to Vault auth and policiesIntermediate key lives in Vault's barrier
AWS Private CAAPI, ACM integrationYour choiceManaged HSM-backed CAPer-CA monthly price
SPIFFE / SPIREWorkload API, X.509-SVID, JWT-SVIDMinutes to hoursAttested identity, federationAnother critical control plane

Fix / how to use it: run a two-tier private PKI (offline root, online intermediate in step-ca, Vault or AWS Private CA), issue workload certificates with lifetimes of hours, distribute trust bundles automatically, and make every server hot-reload certificates (the Go Reloader in this chapter re-reads the files when cert-manager or Vault Agent replaces them).

Secrets management: never in code, one store, audited reads Must-know ​

In plain words: a secret (database password, API key, signing key, OAuth client secret) is stored in one secret manager, read at run time by the workload that needs it, with every read logged, and never written into code, images, CI logs or committed .env files.

Common misunderstanding: "Our repository is private, so a key in the code is fine." Private repositories are cloned to laptops, CI runners and vendors; forks and history keep the key after you delete the line; one compromised developer account exposes all of it. OWASP: "Do not hard-code keys into the application source code" and "Do not check keys into version control systems".

Definition: secrets management is the practice of centralising "the storage, provisioning, auditing, rotation and management of secrets" (OWASP Secrets Management Cheat Sheet). The products: HashiCorp Vault (KV v2 for static secrets, engines for dynamic ones), AWS Secrets Manager (rotation with Lambda functions, cross-region replication), AWS Systems Manager Parameter Store (SecureString parameters encrypted with KMS; cheaper, fewer features), GCP Secret Manager (versioned secrets with IAM per secret), Azure Key Vault (secrets, keys and certificates), Kubernetes Secrets (base64, "by default, stored unencrypted in the API server's underlying data store (etcd)" unless encryption at rest is configured), and the GitOps tools that let you keep encrypted secrets in git: Bitnami sealed-secrets (encrypted to a cluster key, "decrypted only by the controller running in the target cluster"), SOPS (encrypts values in YAML/JSON/ENV files with age, PGP or AWS/GCP/Azure KMS keys) and age (a small file-encryption tool and format, age -r age1...).

text
     Step  Who                 Action
1          platform team       create secret payments/stripe_key in Vault KV v2 (version 1)
2          policy              allow read on secret/data/payments for role payments-api only
3          payments pod        authenticates with its Kubernetes service account (Vault Kubernetes auth)
4          Vault               returns version 3 of the secret, writes an audit log entry
5          security            rotates the key at Stripe, writes version 4; pods pick it up within the cache TTL

Real scenarios: an AWS access key committed to a public repository and abused within minutes; a .env file baked into a Docker image layer; database passwords printed by a framework's debug page; a CI variable echoed into build logs; the same database password used by twelve services, so nobody can tell which one leaked it.

ProductBest forRotationPricing model (shape)Notes
HashiCorp VaultMulti-cloud, dynamic secrets, PKI, transitEngines rotate or issue on demandSelf-hosted or HCPStrongest feature set, you operate it
AWS Secrets ManagerAWS workloads, RDS credentialsManaged rotation with LambdaPer secret per month + API callsNative RDS/Redshift/DocumentDB rotation
AWS SSM Parameter StoreConfiguration plus some secretsNone built inStandard parameters freeSecureString uses KMS
GCP Secret ManagerGCP workloadsRotation notifications (Pub/Sub)Per version + accessIAM per secret, regional replication policies
Azure Key VaultAzure workloadsRotation policies for keys/certsPer operationSecrets, keys, certificates in one place
Kubernetes SecretDelivery into podsNoneFreeEnable etcd encryption with a KMS provider
sealed-secrets / SOPS + ageGitOps repositoriesRe-encrypt and commitFreeGit holds ciphertext; key management moves to the cluster or the KMS

Fix / how to use it: one store per environment, one secret per consumer where possible, read access per workload identity (IAM role, Kubernetes service account), an audit log you actually alert on, and secret scanning on every commit (see Secret sprawl).

Dynamic secrets, leases and rotation Important ​

In plain words: instead of one long-lived database password, each application instance asks for its own username and password that expire automatically in an hour. A leaked credential is short-lived and traceable to one instance.

Common misunderstanding: "Restarting the app rotates its credentials." OWASP: "Restarting the application does not itself revoke stolen credentials; they remain usable until the backing service expires or revokes them." Rotation and revocation happen in the secret backend, not in your process.

Definition: a dynamic secret is generated on request by the secrets backend (Vault database, AWS, GCP and PKI engines). Vault: "With every dynamic secret and service type authentication token, Vault creates a lease: metadata containing information such as a time duration, renewability, and more"; "All dynamic secrets in Vault are required to have a lease"; the lease id is used to renew or revoke, and revocation "invalidates that secret immediately". Static secret rotation (AWS Secrets Manager rotation functions, Vault static roles with rotation_period) changes one long-lived secret on a schedule, usually with a two-phase scheme (create the new credential, switch clients, retire the old) so that no instance holds an invalid password mid-rotation. OWASP lists the rotation styles: gradual, rapid and scheduled.

text
     t        Event                                         Vault lease                     PostgreSQL
1    00:00    pod A: GET /v1/database/creds/orders-rw       lease .../abc, TTL 1h           CREATE ROLE v-orders-rw-x1 VALID UNTIL ...
2    00:40    pod A renews the lease                        TTL extended to 01:40            unchanged
3    01:10    pod A deleted (scale down)                    lease not renewed                still valid until expiry
4    01:40    lease expires                                 Vault revokes                    DROP ROLE v-orders-rw-x1
5    any time incident: vault lease revoke -prefix ...      all leases of the role revoked  every generated role dropped

Real scenarios: per-pod PostgreSQL users through the Vault database engine; short-lived AWS credentials from the Vault AWS engine or from IAM roles for service accounts; RDS master password rotation in AWS Secrets Manager; CI jobs that receive a 15-minute token through OIDC federation instead of a stored cloud key.

ApproachLifetimeBlast radius of a leakCost
Static shared passwordYearsEvery service, untraceableCheap until it leaks
Static, rotated on schedule (Secrets Manager, Vault static role)Days to monthsEvery holder until the next rotationRotation logic and client reloads
Dynamic per instance (Vault database engine)Minutes to hoursOne instance, traceable by usernameVault availability is on the critical path; many DB roles
Workload identity, no secret (IAM roles, GCP workload identity, SPIFFE)Minutes, automaticOne workload, short windowBest option when the target supports it

Fix / how to use it: prefer workload identity where the target supports it (cloud APIs, IAM database authentication), dynamic secrets where it does not, and scheduled rotation for the rest; make every client able to reload credentials without a restart (connection pools that re-read the password on reconnect).

Secret injection patterns: env, file, sidecar, API Important ​

In plain words: there are four ways a secret reaches a running process. Each one trades simplicity for safety and freshness.

Common misunderstanding: "Environment variables are the twelve-factor way, so they are the secure way." Environment variables are inherited by child processes, appear in /proc/<pid>/environ for the same user, in crash dumps, in docker inspect and in debug pages. OWASP: "Using environment variables is therefore not recommended unless the other methods are not possible."

Definition: (1) environment variables set by the orchestrator at start, never refreshed; (2) mounted files (Kubernetes Secret volumes, the Secrets Store CSI Driver, Docker secrets in /run/secrets), which can be rotated in place and protected with file permissions; (3) a sidecar or agent (Vault Agent, the AWS Secrets Manager agent, the Vault Agent Injector for Kubernetes) that authenticates, renews leases, and writes files or templates; (4) a direct API call from the application with its workload identity, which supports dynamic secrets but couples the code to the store. The External Secrets Operator (ESO) syncs ExternalSecret resources from a SecretStore or ClusterSecretStore (Vault, AWS, GCP, Azure) into native Kubernetes Secrets.

Secret storeVault, Secrets Manager, Secret ManagerEnvironmentset once at startno refresh; leaks to childrenMounted fileK8s Secret, CSI, ESO0400, rotates in placeSidecar / agentVault Agent, renews leaseswrites files or proxiesAPI in codeworkload identity logindynamic secrets, leasesApplication processnever logs a secret; reloads on change; holds the shortest-lived credential that works
text
     Pattern       Rotation picked up                    Where it can leak
1    env var       only on restart                       child processes, crash dumps, docker inspect, debug pages
2    file mount    when kubelet/CSI updates the file     anyone with exec into the pod, backups of the volume
3    sidecar       on lease renewal / template change    the shared volume between agent and app
4    API call      immediately, per call or per TTL      the app's own memory and logs

Real scenarios: Laravel on Kubernetes with .env rendered by Vault Agent from a template, then php artisan config:cache; a Go service reading /var/run/secrets/db/password and reloading on change; ESO syncing an AWS Secrets Manager secret into a Kubernetes Secret consumed as a file; a Lambda function reading Secrets Manager through the parameters and secrets extension with a local cache.

PatternProductsRefreshCode couplingUse when
Env varKubernetes env.valueFrom.secretKeyRef, ECS secrets, Docker -eRestartNoneShort-lived processes, legacy apps
FileKubernetes Secret volume, Secrets Store CSI Driver, Docker secretsAutomatic (eventually)Read a fileDefault for containers
Sidecar / agentVault Agent, Vault Agent Injector, AWS Secrets Manager agentLease-drivenRead a file or call localhostDynamic secrets without SDK code
APIVault SDK, AWS SDK, GCP client librariesPer callHighWhen the app must request per-tenant or per-job secrets
GitOps syncESO, sealed-secrets, SOPS (with Flux or Argo CD)On syncNoneDeclarative clusters

Fix / how to use it: default to files mounted with 0400 permissions, reloaded on change; use an agent for dynamic secrets; keep env vars for non-sensitive configuration; and make the application's secret type refuse to print (the Go secrets.Secret type prints [REDACTED] through fmt, slog and JSON).

Secret sprawl and detection: gitleaks and trufflehog Important ​

In plain words: secrets spread into places nobody planned: git history, CI logs, tickets, chat, wiki pages, container images. Scanners find them; rotation is the only real fix once they are found.

Common misunderstanding: "We removed the key in the next commit." The key stays in history, in every clone and fork, and in any mirror; public GitHub is scraped for keys continuously. Deleting is not remediation: revoking and rotating the key is.

Definition: secret sprawl is the uncontrolled spread of credentials across systems. Detection tools: gitleaks (regex and entropy rules, gitleaks git for repositories, gitleaks dir for directories, available as a pre-commit hook and a GitHub Action) and TruffleHog (hundreds of detectors that can verify a found credential against the provider, trufflehog git <url> --results=verified, and scan "Git, chats, wikis, logs, API testing platforms, object stores, filesystems and more"). Platform features: GitHub secret scanning and push protection, GitLab secret detection.

text
     Minute  Event
1    0       developer commits config/aws.php with an access key to a public repository
2    1       push protection is off; key is public
3    5       automated scrapers find the key, start crypto-mining instances
4    20      cloud provider or the scanner alerts
5    25      response: deactivate the key, rotate, review CloudTrail, then rewrite history (last, not first)

Real scenarios: a pre-commit hook blocks an RSA private key; a nightly TruffleHog scan of all repositories finds a verified Slack webhook in a three-year-old commit; a container image scan finds .env in a layer; CI logs scanned for tokens printed by a debug flag.

ToolWhere it runsVerificationNotes
gitleakspre-commit, CI, gitleaks git / gitleaks dirNo (pattern + entropy)Fast, simple config, baseline files for old findings
TruffleHogCI, scheduled scans, many sourcesYes, --results=verifiedFewer false positives, slower
GitHub secret scanning + push protectionOn push to GitHubPartner validationBlocks known token formats before they land
Container scanners (Trivy, Grype)Image buildsNoFind secrets and keys in layers

Fix / how to use it: pre-commit plus CI scanning (block new leaks), a scheduled full-history scan (find old ones), and a runbook that starts with "revoke and rotate", then "check access logs", then "clean history".

Signing artefacts: Sigstore, cosign and SLSA Good to know ​

In plain words: sign what you build (container images, binaries, packages) so that deployers can verify it came from your pipeline and was not changed. Sigstore makes this possible without managing long-lived signing keys.

Common misunderstanding: "A signature proves the artefact is safe." A signature proves who signed it, not what is inside. Provenance (how and from what source it was built) and policy at deploy time (only admit images signed by this pipeline identity) turn a signature into a control.

Definition: Sigstore is a set of services for signing: Fulcio (a CA that "issues short-lived certificates binding an ephemeral key to an OpenID Connect identity") and Rekor (a transparency log: "Signing events are logged in Rekor, a signature transparency log"). cosign signs and verifies container images and blobs (cosign sign, cosign verify --certificate-identity ... --certificate-oidc-issuer ...); keyless signing "associates identities, rather than keys, with an artifact signature". SLSA (Supply-chain Levels for Software Artifacts) v1.0 defines build levels: "Build L0: No guarantees", "Build L1: Provenance exists", "Build L2: Hosted build platform", "Build L3: Hardened builds".

text
     Step  CI (GitHub Actions)                                 Cluster admission (Kyverno / Sigstore policy-controller)
1          build image, push digest sha256:...                 
2          cosign sign: OIDC token -> Fulcio cert (10 min)     
3          signature + certificate logged in Rekor              
4          SLSA provenance attestation attached                 
5                                                              verify: identity = repo workflow, issuer = GitHub OIDC
6                                                              admit only matching digests; reject unsigned images

Real scenarios: Kubernetes admission that admits only images signed by https://github.com/example/app/.github/workflows/release.yml; npm provenance for published packages; Go module checksums through the checksum database as a related transparency mechanism; firmware signed with an HSM-held key where keyless signing is not allowed.

OptionKey managementVerification identityTransparency
cosign keyless (Sigstore)Ephemeral keys, Fulcio certificatesOIDC identity of the workflowRekor
cosign with a KMS keyAWS/GCP/Azure KMS or Vault keyPublic keyOptional Rekor
GPG-signed releasesLong-lived private keysKey fingerprintNone
Notation (Notary v2)Certificates from your PKIX.509 chainOptional

Fix / how to use it: sign by digest, never by tag; verify identity and issuer, not just "has a signature"; record SLSA provenance; enforce at admission time.

Randomness: crypto/rand and random_bytes Must-know ​

In plain words: keys, nonces, tokens and session ids must come from the operating system's cryptographic random generator, never from a general-purpose random function.

Common misunderstanding: "math/rand seeded with the time is random enough for a reset token." It is predictable: an attacker who knows roughly when the token was created can enumerate the seeds. PHP's mt_rand and uniqid have the same problem.

Definition: a CSPRNG (cryptographically secure pseudo-random number generator) produces output an attacker cannot predict even after seeing previous output. Go's crypto/rand.Read "fills b with cryptographically secure random bytes. It never returns an error, and always fills b entirely" and rand.Text (Go 1.24) returns a base32 string with "at least 128 bits of randomness". PHP's random_bytes() and random_int() use the OS CSPRNG and throw if it is unavailable; Laravel's Str::random and key:generate use it. In FIPS 140-3 mode, Go's crypto/rand.Reader "is implemented in terms of a NIST SP 800-90A DRBG".

text
     Token generator                  Entropy                         Verdict
1    md5(uniqid(mt_rand()))           time + 32-bit PRNG state        predictable
2    math/rand.Int63() seeded by time seconds since an estimate      predictable
3    crypto/rand.Text()               >= 128 bits from the OS         good
4    bin2hex(random_bytes(32))        256 bits from the OS            good

Real scenarios: password-reset tokens, API keys, session ids, CSRF tokens, AES keys and nonces, idempotency keys that must not be guessable, invitation codes.

LanguageUseNever for secrets
Gocrypto/rand.Read, rand.Text, rand.Intmath/rand, math/rand/v2 (fine for jitter)
PHP / Laravelrandom_bytes, random_int, Str::random, Str::passwordrand, mt_rand, uniqid, lcg_value
Node.jscrypto.randomBytes, crypto.randomUUIDMath.random
Pythonsecrets.token_bytes, secrets.token_urlsaferandom

Fix / how to use it: lint for the non-cryptographic generators in security code (gosec G404 flags math/rand), and give every token at least 128 bits of entropy.

Compliance claims, stated carefully Good to know ​

In plain words: "we encrypt everything with military-grade AES" is marketing. Precise claims name the data, the layer, the algorithm, the key owner and the validation.

Common misunderstanding: "AWS is PCI and FIPS compliant, so our system is." Provider attestations cover the provider's part of the shared responsibility model. Your application, its key policies, its logs and its data flows are yours to document and audit.

Definition: useful phrasing: "Customer PII columns are encrypted with AES-256-GCM using per-tenant data keys wrapped by AWS KMS keys; KMS keys reside in FIPS 140-3 Level 3 validated HSMs (as stated by AWS); application cryptography uses the Go Cryptographic Module in FIPS 140-3 mode (GOFIPS140=v1.0.0)". Things to avoid: "FIPS compliant" without a module and certificate; "encrypted at rest" without naming the layer; "end-to-end encrypted" when the server can decrypt; "unbreakable"; "GDPR compliant because encrypted" (encryption is one of the measures Article 32 names, not compliance by itself).

text
     Claim                                   Question an auditor asks
1    "data is encrypted at rest"             which layer? who can decrypt? where are the keys?
2    "FIPS 140-3"                            which module, which certificate, approved mode enabled?
3    "keys are rotated"                      which keys, how often, evidence of the last rotation?
4    "end-to-end encrypted"                  can the operator decrypt? then it is not

Real scenarios: a SOC 2 questionnaire asking about key management; a FedRAMP boundary requiring FIPS-validated modules for all cryptography; a PCI DSS v4 assessment of key custodians and cryptoperiods; a customer contract requiring customer-managed keys (CMK/BYOK).

FrameworkWhat it asks about cryptography (shape)
PCI DSS v4Strong cryptography for stored and transmitted card data, documented key management, key custodians
FIPS 140-3 / FedRAMPValidated modules in approved mode
HIPAA Security RuleEncryption as an addressable safeguard, risk-based
GDPR Art. 32Encryption and pseudonymisation as appropriate measures
SOC 2Documented controls and evidence over time

Fix / how to use it: keep a cryptographic inventory (data class, layer, algorithm, key, owner, rotation evidence) and generate claims from it; the Secure SDLC chapter covers the audit process.

Mechanics ​

Knobs in one place ​

KnobProductValue this chapter recommendsWhy
MinVersionGo crypto/tlstls.VersionTLS12 (or 1.3 internally)Default is 1.2 already; make it explicit
CipherSuitesGo crypto/tlsECDHE + AES-GCM / ChaCha20 onlyAffects TLS 1.2 only
ssl_protocols / ssl_ciphersNGINXTLSv1.2 TLSv1.3, the Intermediate cipher listPublic compatibility
ssl_stapling on; ssl_stapling_verify on;NGINXOn where the CA still runs OCSPNot useful with Let's Encrypt after 2025
Rotation periodAWS KMS365 days (default) or shorter by policyOld material kept automatically
min_decryption_version, auto_rotate_periodVault TransitRaise only after rewrap reaches zeroRetires old versions
convergent_encryption, derivedVault TransitOnly for fields that need equalityDeterministic encryption leaks equality
default_lease_ttl, max_lease_ttlVault1 h / 24 h for database rolesShort credentials
renewBefore, durationcert-manager CertificateRenew at 2/3 of lifetimeRoom for retries
cipher, key, previous_keysLaravel config/app.phpAES-256-CBC (default) or AES-256-GCMRotation via APP_PREVIOUS_KEYS
GOFIPS140, GODEBUG=fips140=onGo toolchainOnly where FIPS is requiredApproved algorithms only in TLS
--encryption-provider-configKubernetes API serverKMS v2 provideretcd Secrets encrypted with a KMS-wrapped DEK

The envelope format, byte by byte ​

FieldSizePurpose
Format version1 byte (0x01)Crypto agility: a new layout or algorithm gets a new version
KEK id length + KEK id1 + up to 255 bytesWhich KMS key wrapped the DEK (rotation, shredding, routing to a region)
KEK version4 bytesWhich version; drives rewrap progress
Wrapped DEK length + wrapped DEK2 + n bytesThe KMS ciphertext blob
Nonce12 bytesRandom, one per DEK
Ciphertext + tagplaintext + 16 bytesAES-256-GCM output

Arithmetic you will be asked for ​

  • Random-nonce budget: 2^32 encryptions per key. At 10,000 encryptions per second that is 119.3 hours (about five days); at 100 per second, 497 days. With a DEK per record the budget applies per record, so it never binds.
  • KMS calls: one GenerateDataKey per write and one Decrypt per read without caching. At 2,000 reads per second that is 2,000 KMS requests per second: possibly within your account's request quota (check the KMS quotas page for your region), but every read pays a network round trip and a per-request charge; a data-key cache with a 5-minute TTL and a message limit turns it into a handful per second (our arithmetic).
  • Certificate renewals: with 47-day certificates renewed at two thirds of lifetime, each certificate renews every ~31 days; 500 certificates mean ~16 renewals per day, every day.
  • Ciphertext growth: AES-GCM adds 12 (nonce) + 16 (tag) bytes plus the envelope header and the wrapped key (a few hundred bytes for KMS blobs); base64 adds a third. A 9-character national id becomes a TEXT value of a few hundred bytes.

Error messages you will see ​

Message (verbatim)WhereMeaningAction
cipher: message authentication failedGo cipher.AEAD.OpenWrong key, wrong AAD, wrong nonce or tampered dataCheck the key version and the AAD binding; do not retry
crypto/aes: invalid key size 31Go aes.NewCipherKey is not 16/24/32 bytes (often a base64 string used as raw bytes)Decode the key
tls: failed to verify certificate: x509: certificate signed by unknown authorityGo TLS clientMissing intermediate or private CA not in RootCAsServe the full chain; add the CA bundle
x509: certificate is valid for example.com, *.example.com, not orders.internal.testGo TLS clientName not in the SANFix the certificate or the ServerName
remote error: tls: protocol version not supportedGo TLS clientServer refused the offered versionsUpgrade the client; do not lower the server
tls: client offered only unsupported versions: [302 301]Go TLS server logA TLS 1.1/1.0 client was refusedExpected after enforcing TLS 1.2
The MAC is invalid.Laravel DecryptExceptionValue encrypted with another key, or modifiedAdd the old key to APP_PREVIOUS_KEYS
The payload is invalid.Laravel DecryptExceptionNot a Laravel encrypted payload (plaintext, truncated column)Check column length and migrations
Unsupported cipher or incorrect key length. Supported ciphers are: ...Laravel EncrypterAPP_KEY length does not match app.cipherRun php artisan key:generate for the cipher
InvalidCiphertextExceptionAWS KMS DecryptWrong encryption context, wrong key, or corrupted blobSend the same context used on encrypt
AccessDeniedExceptionAWS KMSKey policy or IAM denies the callerFix the key policy, not the code
permission denied (HTTP 403)VaultToken lacks the policy for the pathCheck the role's policy
SSL certificate problem: unable to get local issuer certificatecurl / OpenSSLMissing intermediate or rootServe the chain, update the CA bundle

Go ​

Before ​

The first version keeps a key in source code, uses a counter nonce that restarts at zero, stores no key id and binds no associated data. Run it: two different card numbers encrypted with the same key and the same nonce after a simulated restart.

go
// Command before shows a design that works on the first day and fails
// quietly later. It compiles and runs; every comment marked PROBLEM is a
// design flaw, not a bug the compiler can see.
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"log"
)

// PROBLEM 1: the key lives in source code, so it lives in git history,
// in every clone, in CI logs and in every container image forever.
const masterKeyHex = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"

// PROBLEM 2: a counter nonce that starts at zero in every process.
// After a restart, or with two replicas, the same (key, nonce) pair is used
// again: AES-GCM then leaks the XOR of two plaintexts and lets an attacker
// forge tags.
var counter uint64

func encrypt(plaintext []byte) []byte {
	key, _ := hex.DecodeString(masterKeyHex)
	block, err := aes.NewCipher(key)
	if err != nil {
		log.Fatal(err)
	}
	aead, err := cipher.NewGCM(block)
	if err != nil {
		log.Fatal(err)
	}
	nonce := make([]byte, aead.NonceSize())
	counter++
	binary.BigEndian.PutUint64(nonce[4:], counter)
	// PROBLEM 3: no key id and no version in the output. When the key
	// must be rotated there is no way to tell which rows used which key.
	// PROBLEM 4: no associated data. A ciphertext copied from one user's
	// row into another user's row still decrypts without complaint.
	return aead.Seal(nonce, nonce, plaintext, nil)
}

func main() {
	a := encrypt([]byte("card=4111111111111111"))
	// Simulate a restart: the counter is back to zero.
	counter = 0
	b := encrypt([]byte("card=5500000000000004"))
	fmt.Printf("nonce a: %x\n", a[:12])
	fmt.Printf("nonce b: %x\n", b[:12])
	fmt.Println("same nonce, same key:", string(a[:12]) == string(b[:12]))
	// PROBLEM 5: one key for every tenant and every table. Deleting one
	// customer's data cryptographically (crypto-shredding) is impossible,
	// and one leak exposes everything.
}

After ​

The redesign is four packages. kms defines the Wrapper interface a KMS must provide and a local fake with versions, rotation, a minimum decryption version and destruction.

go
// Package kms defines the key-wrapping interface an envelope encrypter needs
// and a local, in-memory fake of a KMS (AWS KMS, Google Cloud KMS, Azure Key
// Vault, HashiCorp Vault Transit) for tests and labs. The fake keeps KEKs in
// process memory: never use it in production, where the KEK must stay inside
// an HSM-backed service and only Wrap/Unwrap calls cross the boundary.
package kms

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"errors"
	"fmt"
	"strconv"
	"sync"
)

// WrappedKey is a DEK encrypted under one version of a named KEK.
type WrappedKey struct {
	KeyID   string // logical KEK name, for example "tenant-42"
	Version int    // KEK version that wrapped this DEK
	Blob    []byte // nonce || ciphertext || tag
}

// Wrapper is what an application needs from a KMS. Real implementations call
// GenerateDataKey/Decrypt/ReEncrypt (AWS KMS), Encrypt/Decrypt (Cloud KMS)
// or transit/encrypt, transit/decrypt, transit/rewrap (Vault).
type Wrapper interface {
	Wrap(ctx context.Context, keyID string, dek, aad []byte) (WrappedKey, error)
	Unwrap(ctx context.Context, wk WrappedKey, aad []byte) ([]byte, error)
	// Rewrap moves a wrapped DEK to the primary KEK version without
	// returning the plaintext DEK to the caller.
	Rewrap(ctx context.Context, wk WrappedKey, aad []byte) (WrappedKey, error)
}

var (
	ErrKeyNotFound     = errors.New("kms: key not found")
	ErrKeyDestroyed    = errors.New("kms: key destroyed")
	ErrVersionDisabled = errors.New("kms: key version below min_decryption_version")
	ErrUnwrap          = errors.New("kms: unwrap failed (wrong key, wrong context or tampered blob)")
)

type ring struct {
	versions   map[int][]byte
	primary    int
	minDecrypt int
	destroyed  bool
}

// Local is an in-memory KMS fake with versions, rotation, a minimum
// decryption version and destruction (crypto-shredding).
type Local struct {
	mu    sync.RWMutex
	rings map[string]*ring
	calls int
}

func NewLocal() *Local { return &Local{rings: map[string]*ring{}} }

// CreateKey creates version 1 of a named KEK.
func (l *Local) CreateKey(keyID string) error {
	l.mu.Lock()
	defer l.mu.Unlock()
	if _, ok := l.rings[keyID]; ok {
		return fmt.Errorf("kms: key %q exists", keyID)
	}
	l.rings[keyID] = &ring{versions: map[int][]byte{1: newKey()}, primary: 1, minDecrypt: 1}
	return nil
}

// Rotate adds a new version and makes it primary. Old versions still
// unwrap, exactly like AWS KMS automatic rotation or Vault transit rotate.
func (l *Local) Rotate(keyID string) (int, error) {
	l.mu.Lock()
	defer l.mu.Unlock()
	r, err := l.ring(keyID)
	if err != nil {
		return 0, err
	}
	r.primary++
	r.versions[r.primary] = newKey()
	return r.primary, nil
}

// SetMinDecryptionVersion refuses unwrap for older versions (Vault's
// min_decryption_version). Run it only after every DEK has been rewrapped.
func (l *Local) SetMinDecryptionVersion(keyID string, v int) error {
	l.mu.Lock()
	defer l.mu.Unlock()
	r, err := l.ring(keyID)
	if err != nil {
		return err
	}
	if v < 1 || v > r.primary {
		return fmt.Errorf("kms: version %d out of range", v)
	}
	r.minDecrypt = v
	return nil
}

// Destroy erases every version. Every DEK wrapped by this KEK, and so every
// ciphertext under those DEKs, becomes unreadable: crypto-shredding.
func (l *Local) Destroy(keyID string) error {
	l.mu.Lock()
	defer l.mu.Unlock()
	r, err := l.ring(keyID)
	if err != nil {
		return err
	}
	for v, k := range r.versions {
		clear(k)
		delete(r.versions, v)
	}
	r.destroyed = true
	return nil
}

// Calls reports how many Wrap/Unwrap/Rewrap requests reached the fake, so
// tests can prove a DEK cache really saves KMS round trips.
func (l *Local) Calls() int {
	l.mu.RLock()
	defer l.mu.RUnlock()
	return l.calls
}

func (l *Local) Wrap(_ context.Context, keyID string, dek, aad []byte) (WrappedKey, error) {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.calls++
	r, err := l.ring(keyID)
	if err != nil {
		return WrappedKey{}, err
	}
	blob, err := seal(r.versions[r.primary], dek, bindAAD(keyID, r.primary, aad))
	if err != nil {
		return WrappedKey{}, err
	}
	return WrappedKey{KeyID: keyID, Version: r.primary, Blob: blob}, nil
}

func (l *Local) Unwrap(_ context.Context, wk WrappedKey, aad []byte) ([]byte, error) {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.calls++
	return l.unwrapLocked(wk, aad)
}

func (l *Local) Rewrap(_ context.Context, wk WrappedKey, aad []byte) (WrappedKey, error) {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.calls++
	dek, err := l.unwrapLocked(wk, aad)
	if err != nil {
		return WrappedKey{}, err
	}
	defer clear(dek)
	r := l.rings[wk.KeyID]
	blob, err := seal(r.versions[r.primary], dek, bindAAD(wk.KeyID, r.primary, aad))
	if err != nil {
		return WrappedKey{}, err
	}
	return WrappedKey{KeyID: wk.KeyID, Version: r.primary, Blob: blob}, nil
}

func (l *Local) unwrapLocked(wk WrappedKey, aad []byte) ([]byte, error) {
	r, err := l.ring(wk.KeyID)
	if err != nil {
		return nil, err
	}
	if wk.Version < r.minDecrypt {
		return nil, ErrVersionDisabled
	}
	kek, ok := r.versions[wk.Version]
	if !ok {
		return nil, ErrKeyNotFound
	}
	dek, err := open(kek, wk.Blob, bindAAD(wk.KeyID, wk.Version, aad))
	if err != nil {
		return nil, ErrUnwrap
	}
	return dek, nil
}

func (l *Local) ring(keyID string) (*ring, error) {
	r, ok := l.rings[keyID]
	if !ok {
		return nil, ErrKeyNotFound
	}
	if r.destroyed {
		return nil, ErrKeyDestroyed
	}
	return r, nil
}

// bindAAD ties the wrapped DEK to the KEK name, the KEK version and the
// caller's context (AWS KMS calls this the encryption context).
func bindAAD(keyID string, version int, aad []byte) []byte {
	b := []byte("kek=" + keyID + ";v=" + strconv.Itoa(version) + ";ctx=")
	return append(b, aad...)
}

func newKey() []byte {
	k := make([]byte, 32)
	rand.Read(k) // never returns an error; crashes the program if the OS fails
	return k
}

// A KEK wraps few DEKs, far below the 2^32 random-nonce limit of NIST
// SP 800-38D, so a random 96-bit nonce is safe here.
func seal(key, plaintext, aad []byte) ([]byte, error) {
	aead, err := newGCM(key)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, aead.NonceSize())
	rand.Read(nonce)
	return aead.Seal(nonce, nonce, plaintext, aad), nil
}

func open(key, blob, aad []byte) ([]byte, error) {
	aead, err := newGCM(key)
	if err != nil {
		return nil, err
	}
	if len(blob) < aead.NonceSize()+aead.Overhead() {
		return nil, ErrUnwrap
	}
	n := aead.NonceSize()
	return aead.Open(nil, blob[:n], blob[n:], aad)
}

func newGCM(key []byte) (cipher.AEAD, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return cipher.NewGCM(block)
}

envelope generates a fresh AES-256-GCM DEK per message, binds the record identity as AAD, wraps the DEK through the Wrapper, and serializes a versioned envelope with the KEK id and version. Rewrap changes only the wrapped DEK. blindindex.go derives per-purpose keys with HKDF and computes HMAC-SHA-256 blind indexes.

go
// Package envelope implements envelope encryption: a fresh AES-256-GCM data
// encryption key (DEK) per message, wrapped by a key encryption key (KEK)
// that never leaves the KMS. The serialized envelope carries the KEK id and
// version, so rotation and rewrapping are bookkeeping, not archaeology.
package envelope

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/binary"
	"errors"
	"fmt"

	"academy/cryptography-tls-pki-secrets/kms"
)

// FormatV1 is the first byte of every envelope. Bump it when the layout or
// the algorithm changes (crypto agility), and keep a decoder for old formats.
const FormatV1 byte = 1

var ErrMalformed = errors.New("envelope: malformed")

// Envelope is what gets stored next to the data (one column, one blob).
type Envelope struct {
	KEK        kms.WrappedKey
	Nonce      []byte
	Ciphertext []byte // includes the 16-byte GCM tag
}

// Encrypter seals and opens envelopes through a kms.Wrapper.
type Encrypter struct{ kms kms.Wrapper }

func New(w kms.Wrapper) *Encrypter { return &Encrypter{kms: w} }

// Encrypt generates a DEK, encrypts plaintext with it, wraps the DEK under
// kekID and returns the serialized envelope. aad must identify where the
// value lives (table, column, row id, tenant): the same aad is required to
// decrypt, so a ciphertext copied into another row fails to open.
func (e *Encrypter) Encrypt(ctx context.Context, kekID string, plaintext, aad []byte) ([]byte, error) {
	dek := make([]byte, 32)
	rand.Read(dek)
	defer clear(dek) // best effort: Go may have copied it, but do not keep it around

	// One message per DEK, so a random 96-bit nonce can never repeat
	// under this key.
	nonce := make([]byte, 12)
	rand.Read(nonce)
	ct, err := sealAESGCM(dek, nonce, plaintext, aad)
	if err != nil {
		return nil, err
	}
	wk, err := e.kms.Wrap(ctx, kekID, dek, aad)
	if err != nil {
		return nil, fmt.Errorf("envelope: wrap DEK: %w", err)
	}
	return Envelope{KEK: wk, Nonce: nonce, Ciphertext: ct}.MarshalBinary()
}

// Decrypt parses the envelope, asks the KMS to unwrap the DEK and opens the
// ciphertext.
func (e *Encrypter) Decrypt(ctx context.Context, blob, aad []byte) ([]byte, error) {
	env, err := Parse(blob)
	if err != nil {
		return nil, err
	}
	dek, err := e.kms.Unwrap(ctx, env.KEK, aad)
	if err != nil {
		return nil, fmt.Errorf("envelope: unwrap DEK: %w", err)
	}
	defer clear(dek)
	pt, err := openAESGCM(dek, env.Nonce, env.Ciphertext, aad)
	if err != nil {
		return nil, fmt.Errorf("envelope: open: %w", err)
	}
	return pt, nil
}

// Rewrap moves the envelope's DEK to the KEK's primary version. The data
// ciphertext is untouched and the application never sees the DEK. It
// reports whether anything changed, so a batch job can count its progress.
func (e *Encrypter) Rewrap(ctx context.Context, blob, aad []byte) ([]byte, bool, error) {
	env, err := Parse(blob)
	if err != nil {
		return nil, false, err
	}
	wk, err := e.kms.Rewrap(ctx, env.KEK, aad)
	if err != nil {
		return nil, false, fmt.Errorf("envelope: rewrap: %w", err)
	}
	if wk.Version == env.KEK.Version {
		return blob, false, nil
	}
	env.KEK = wk
	out, err := env.MarshalBinary()
	return out, err == nil, err
}

// MarshalBinary layout (all lengths big-endian):
//
//	format(1) | len(keyID)(1) | keyID | kekVersion(4) | len(wrapped)(2) |
//	wrapped | nonce(12) | ciphertext+tag
func (env Envelope) MarshalBinary() ([]byte, error) {
	if len(env.KEK.KeyID) == 0 || len(env.KEK.KeyID) > 255 || len(env.KEK.Blob) > 65535 || len(env.Nonce) != 12 {
		return nil, ErrMalformed
	}
	b := make([]byte, 0, 1+1+len(env.KEK.KeyID)+4+2+len(env.KEK.Blob)+12+len(env.Ciphertext))
	b = append(b, FormatV1, byte(len(env.KEK.KeyID)))
	b = append(b, env.KEK.KeyID...)
	b = binary.BigEndian.AppendUint32(b, uint32(env.KEK.Version))
	b = binary.BigEndian.AppendUint16(b, uint16(len(env.KEK.Blob)))
	b = append(b, env.KEK.Blob...)
	b = append(b, env.Nonce...)
	return append(b, env.Ciphertext...), nil
}

// Parse decodes a FormatV1 envelope and rejects anything else.
func Parse(b []byte) (Envelope, error) {
	if len(b) < 2 || b[0] != FormatV1 {
		return Envelope{}, ErrMalformed
	}
	n := int(b[1])
	p := 2
	if n == 0 || len(b) < p+n+4+2 {
		return Envelope{}, ErrMalformed
	}
	keyID := string(b[p : p+n])
	p += n
	version := int(binary.BigEndian.Uint32(b[p:]))
	p += 4
	wl := int(binary.BigEndian.Uint16(b[p:]))
	p += 2
	if len(b) < p+wl+12+16 {
		return Envelope{}, ErrMalformed
	}
	env := Envelope{
		KEK:        kms.WrappedKey{KeyID: keyID, Version: version, Blob: append([]byte(nil), b[p:p+wl]...)},
		Nonce:      append([]byte(nil), b[p+wl:p+wl+12]...),
		Ciphertext: append([]byte(nil), b[p+wl+12:]...),
	}
	return env, nil
}

func sealAESGCM(key, nonce, plaintext, aad []byte) ([]byte, error) {
	aead, err := gcm(key)
	if err != nil {
		return nil, err
	}
	return aead.Seal(nil, nonce, plaintext, aad), nil
}

func openAESGCM(key, nonce, ciphertext, aad []byte) ([]byte, error) {
	aead, err := gcm(key)
	if err != nil {
		return nil, err
	}
	return aead.Open(nil, nonce, ciphertext, aad)
}

func gcm(key []byte) (cipher.AEAD, error) {
	if len(key) != 32 {
		return nil, fmt.Errorf("envelope: AES-256 needs a 32-byte key, got %d", len(key))
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return cipher.NewGCM(block)
}
go
package envelope

import (
	"crypto/hkdf"
	"crypto/hmac"
	"crypto/sha256"
	"strings"
)

// DeriveKey derives an independent 32-byte subkey for one purpose from a
// root secret with HKDF-SHA-256 (RFC 5869). One root, many purposes:
// "blind-index/users.email/v1", "hmac/webhooks/v1", ... Never reuse one key
// for two purposes.
func DeriveKey(root, salt []byte, purpose string) ([]byte, error) {
	return hkdf.Key(sha256.New, root, salt, purpose, 32)
}

// BlindIndex returns HMAC-SHA-256(key, normalized value), truncated to 16
// bytes. Store it in its own indexed column to find rows by exact match
// without decrypting them. It is deterministic on purpose, so it leaks
// equality (and frequency): never build one over a low-cardinality field
// such as a country, a boolean or a birth year.
func BlindIndex(key []byte, value string) []byte {
	m := hmac.New(sha256.New, key)
	m.Write([]byte(strings.ToLower(strings.TrimSpace(value))))
	return m.Sum(nil)[:16]
}

// Equal compares two MACs in constant time. Never compare MACs or tokens
// with bytes.Equal or ==.
func Equal(a, b []byte) bool { return hmac.Equal(a, b) }

The tests check the AES-256-GCM primitive against NIST CAVP vectors (gcmEncryptExtIV256.rsp and a FAIL case from gcmDecrypt256.rsp), HKDF against RFC 5869 Test Case 1, and then the design: fresh DEKs, AAD binding a ciphertext to its row, tamper detection, rotate then rewrap then retire, crypto-shredding of one tenant, and envelope parsing.

go
package envelope

import (
	"bytes"
	"context"
	"crypto/hkdf"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"testing"

	"academy/cryptography-tls-pki-secrets/kms"
)

func unhex(t *testing.T, s string) []byte {
	t.Helper()
	b, err := hex.DecodeString(s)
	if err != nil {
		t.Fatal(err)
	}
	return b
}

// NIST CAVP gcmEncryptExtIV256.rsp, [Keylen = 256] [IVlen = 96]
// [PTlen = 128] [AADlen = 128] [Taglen = 128], Count = 0.
func TestCAVPEncryptVector(t *testing.T) {
	key := unhex(t, "92e11dcdaa866f5ce790fd24501f92509aacf4cb8b1339d50c9c1240935dd08b")
	iv := unhex(t, "ac93a1a6145299bde902f21a")
	pt := unhex(t, "2d71bcfa914e4ac045b2aa60955fad24")
	aad := unhex(t, "1e0889016f67601c8ebea4943bc23ad6")
	want := unhex(t, "8995ae2e6df3dbf96fac7b7137bae67f"+"eca5aa77d51d4a0a14d9c51e1da474ab")
	got, err := sealAESGCM(key, iv, pt, aad)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(got, want) {
		t.Fatalf("ciphertext||tag = %x, want %x", got, want)
	}
}

// NIST CAVP gcmDecrypt256.rsp, same parameter block: Count = 0 decrypts,
// Count = 2 is marked FAIL and must be rejected.
func TestCAVPDecryptVectors(t *testing.T) {
	ok := struct{ key, iv, ct, aad, tag, pt string }{
		"54e352ea1d84bfe64a1011096111fbe7668ad2203d902a01458c3bbd85bfce14",
		"df7c3bca00396d0c018495d9", "426e0efc693b7be1f3018db7ddbb7e4d",
		"7e968d71b50c1f11fd001f3fef49d045", "ee8257795be6a1164d7e1d2d6cac77a7",
		"85fc3dfad9b5a8d3258e4fc44571bd3b",
	}
	pt, err := openAESGCM(unhex(t, ok.key), unhex(t, ok.iv), unhex(t, ok.ct+ok.tag), unhex(t, ok.aad))
	if err != nil || !bytes.Equal(pt, unhex(t, ok.pt)) {
		t.Fatalf("Count 0: pt=%x err=%v", pt, err)
	}
	fail := struct{ key, iv, ct, aad, tag string }{
		"9a0343f850a6427120f764789ffec6d237447b898fbf51d2182f065d3861497d",
		"3deef6f453dd70d92143adcd", "e93165935ac18e3a2845d15fe31a9286",
		"dbb8226a624520863db6897017b2a4f8", "f5fc50d18766bc3d9e16dd136d45816b",
	}
	if _, err := openAESGCM(unhex(t, fail.key), unhex(t, fail.iv), unhex(t, fail.ct+fail.tag), unhex(t, fail.aad)); err == nil {
		t.Fatal("Count 2 (FAIL) was accepted")
	}
}

// RFC 5869 Appendix A.1, Test Case 1 (HKDF-SHA-256).
func TestHKDFRFC5869Vector(t *testing.T) {
	ikm := bytes.Repeat([]byte{0x0b}, 22)
	salt := unhex(t, "000102030405060708090a0b0c")
	info := string(unhex(t, "f0f1f2f3f4f5f6f7f8f9"))
	want := unhex(t, "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865")
	got, err := hkdf.Key(sha256.New, ikm, salt, info, 42)
	if err != nil || !bytes.Equal(got, want) {
		t.Fatalf("OKM = %x, err %v", got, err)
	}
	k1, _ := DeriveKey(ikm, salt, "blind-index/users.email/v1")
	k2, _ := DeriveKey(ikm, salt, "hmac/webhooks/v1")
	if bytes.Equal(k1, k2) {
		t.Fatal("different purposes must give different keys")
	}
}

func setup(t *testing.T, keys ...string) (*kms.Local, *Encrypter) {
	t.Helper()
	l := kms.NewLocal()
	for _, k := range keys {
		if err := l.CreateKey(k); err != nil {
			t.Fatal(err)
		}
	}
	return l, New(l)
}

func TestRoundTripAndFreshDEK(t *testing.T) {
	ctx := context.Background()
	_, e := setup(t, "tenant-1")
	aad := []byte("patients.ssn#1001")
	a, err := e.Encrypt(ctx, "tenant-1", []byte("078-05-1120"), aad)
	if err != nil {
		t.Fatal(err)
	}
	b, _ := e.Encrypt(ctx, "tenant-1", []byte("078-05-1120"), aad)
	if bytes.Equal(a, b) {
		t.Fatal("same plaintext must give different envelopes (fresh DEK and nonce)")
	}
	ea, _ := Parse(a)
	eb, _ := Parse(b)
	if bytes.Equal(ea.KEK.Blob, eb.KEK.Blob) {
		t.Fatal("each message must have its own wrapped DEK")
	}
	pt, err := e.Decrypt(ctx, a, aad)
	if err != nil || string(pt) != "078-05-1120" {
		t.Fatalf("got %q, %v", pt, err)
	}
}

func TestAADBindsCiphertextToRow(t *testing.T) {
	ctx := context.Background()
	_, e := setup(t, "tenant-1")
	blob, _ := e.Encrypt(ctx, "tenant-1", []byte("secret"), []byte("patients.ssn#1001"))
	if _, err := e.Decrypt(ctx, blob, []byte("patients.ssn#1002")); err == nil {
		t.Fatal("a ciphertext moved to another row must not decrypt")
	}
}

func TestTamperedCiphertextRejected(t *testing.T) {
	ctx := context.Background()
	_, e := setup(t, "tenant-1")
	aad := []byte("row#7")
	blob, _ := e.Encrypt(ctx, "tenant-1", []byte("amount=100"), aad)
	blob[len(blob)-1] ^= 0x01
	if _, err := e.Decrypt(ctx, blob, aad); err == nil {
		t.Fatal("flipped bit was accepted")
	}
}

func TestRotateRewrapThenRetireOldVersion(t *testing.T) {
	ctx := context.Background()
	l, e := setup(t, "tenant-1")
	aad := []byte("row#9")
	v1, _ := e.Encrypt(ctx, "tenant-1", []byte("hello"), aad)

	if v, _ := l.Rotate("tenant-1"); v != 2 {
		t.Fatalf("rotate gave version %d", v)
	}
	// Old envelopes still decrypt after rotation: the key ring keeps v1.
	if _, err := e.Decrypt(ctx, v1, aad); err != nil {
		t.Fatalf("v1 after rotate: %v", err)
	}
	v2, changed, err := e.Rewrap(ctx, v1, aad)
	if err != nil || !changed {
		t.Fatalf("rewrap: changed=%v err=%v", changed, err)
	}
	env1, _ := Parse(v1)
	env2, _ := Parse(v2)
	if env2.KEK.Version != 2 || !bytes.Equal(env1.Ciphertext, env2.Ciphertext) {
		t.Fatal("rewrap must change only the wrapped DEK, not the data ciphertext")
	}
	if _, again, _ := e.Rewrap(ctx, v2, aad); again {
		t.Fatal("rewrapping an up-to-date envelope must be a no-op")
	}
	if err := l.SetMinDecryptionVersion("tenant-1", 2); err != nil {
		t.Fatal(err)
	}
	if _, err := e.Decrypt(ctx, v1, aad); !errors.Is(err, kms.ErrVersionDisabled) {
		t.Fatalf("v1 after retire: %v", err)
	}
	if pt, err := e.Decrypt(ctx, v2, aad); err != nil || string(pt) != "hello" {
		t.Fatalf("v2 after retire: %q %v", pt, err)
	}
}

func TestCryptoShreddingOneTenant(t *testing.T) {
	ctx := context.Background()
	l, e := setup(t, "tenant-1", "tenant-2")
	aad := []byte("row#1")
	t1, _ := e.Encrypt(ctx, "tenant-1", []byte("t1 data"), aad)
	t2, _ := e.Encrypt(ctx, "tenant-2", []byte("t2 data"), aad)
	if err := l.Destroy("tenant-1"); err != nil {
		t.Fatal(err)
	}
	if _, err := e.Decrypt(ctx, t1, aad); !errors.Is(err, kms.ErrKeyDestroyed) {
		t.Fatalf("tenant-1 after shred: %v", err)
	}
	if _, err := e.Decrypt(ctx, t2, aad); err != nil {
		t.Fatalf("tenant-2 must be unaffected: %v", err)
	}
}

func TestParseRejectsGarbage(t *testing.T) {
	for _, b := range [][]byte{nil, {0}, {2, 1, 'a'}, {1, 0}, {1, 3, 'a', 'b', 'c', 0, 0, 0, 1, 0, 5}} {
		if _, err := Parse(b); !errors.Is(err, ErrMalformed) {
			t.Fatalf("Parse(%x) = %v", b, err)
		}
	}
}

func TestBlindIndex(t *testing.T) {
	k, _ := DeriveKey([]byte("root secret from KMS, 32 bytes!!"), nil, "blind-index/users.email/v1")
	a := BlindIndex(k, "Alice@Example.com ")
	b := BlindIndex(k, "alice@example.com")
	if !Equal(a, b) {
		t.Fatal("normalized values must give the same index")
	}
	other, _ := DeriveKey([]byte("another root secret, 32 bytes!!!"), nil, "blind-index/users.email/v1")
	if Equal(a, BlindIndex(other, "alice@example.com")) {
		t.Fatal("the index must depend on the key")
	}
}

tlsconfig builds server and client configurations (TLS 1.2 minimum, AEAD-only 1.2 suites, Go's default hybrid post-quantum key exchange, optional client certificates for mTLS), an http.Server with timeouts, HSTS, and a Reloader that hot-swaps certificates renewed on disk.

go
// Package tlsconfig builds modern crypto/tls configurations for servers and
// clients, and reloads certificates from disk without a restart, which is
// what short-lived certificates (ACME, cert-manager, step-ca, Vault PKI,
// SPIRE) require.
package tlsconfig

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"net/http"
	"os"
	"sync"
	"time"
)

// tls12Suites lists only ECDHE + AEAD suites for TLS 1.2 peers (forward
// secrecy, no CBC, no RSA key exchange). TLS 1.3 suites are not
// configurable in Go: TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384 and
// TLS_CHACHA20_POLY1305_SHA256 are always enabled.
var tls12Suites = []uint16{
	tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
	tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
	tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
	tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
	tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
}

// Reloader serves the current certificate and re-reads the files when they
// change on disk (cert-manager and Vault Agent rewrite them in place).
type Reloader struct {
	certFile, keyFile string
	mu                sync.RWMutex
	cert              *tls.Certificate
	modTime           time.Time
}

func NewReloader(certFile, keyFile string) (*Reloader, error) {
	r := &Reloader{certFile: certFile, keyFile: keyFile}
	if err := r.Reload(); err != nil {
		return nil, err
	}
	return r, nil
}

// Reload reads the key pair if the certificate file changed. A broken new
// file keeps the old certificate in service and returns the error.
func (r *Reloader) Reload() error {
	st, err := os.Stat(r.certFile)
	if err != nil {
		return err
	}
	r.mu.RLock()
	same := r.cert != nil && st.ModTime().Equal(r.modTime)
	r.mu.RUnlock()
	if same {
		return nil
	}
	c, err := tls.LoadX509KeyPair(r.certFile, r.keyFile)
	if err != nil {
		return fmt.Errorf("tlsconfig: reload: %w", err)
	}
	r.mu.Lock()
	r.cert, r.modTime = &c, st.ModTime()
	r.mu.Unlock()
	return nil
}

// GetCertificate plugs into tls.Config. It checks the file at most once per
// handshake; production code would rather reload on a timer or fsnotify.
func (r *Reloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
	_ = r.Reload() // keep serving the old cert if the new one is broken
	r.mu.RLock()
	defer r.mu.RUnlock()
	if r.cert == nil {
		return nil, errors.New("tlsconfig: no certificate loaded")
	}
	return r.cert, nil
}

// Server returns a server config: TLS 1.2 minimum (1.3 preferred by Go),
// AEAD-only 1.2 suites, Go's default key exchanges (X25519MLKEM768 hybrid
// post-quantum since Go 1.24, then X25519, P-256...). Pass clientCAs to
// require client certificates (mTLS); nil means server-only TLS.
func Server(get func(*tls.ClientHelloInfo) (*tls.Certificate, error), clientCAs *x509.CertPool) *tls.Config {
	cfg := &tls.Config{
		MinVersion:     tls.VersionTLS12,
		CipherSuites:   tls12Suites,
		GetCertificate: get,
		NextProtos:     []string{"h2", "http/1.1"},
	}
	if clientCAs != nil {
		cfg.ClientCAs = clientCAs
		cfg.ClientAuth = tls.RequireAndVerifyClientCert
	}
	return cfg
}

// Client returns a client config that trusts roots (nil means the system
// pool) and verifies the server name. It never sets InsecureSkipVerify.
func Client(roots *x509.CertPool, serverName string) *tls.Config {
	return &tls.Config{
		MinVersion:   tls.VersionTLS12,
		CipherSuites: tls12Suites,
		RootCAs:      roots,
		ServerName:   serverName,
	}
}

// HTTPServer wires the TLS config into an http.Server with timeouts, so a
// slow client cannot hold a TLS handshake or a connection open forever.
func HTTPServer(addr string, h http.Handler, cfg *tls.Config) *http.Server {
	return &http.Server{
		Addr:              addr,
		Handler:           h,
		TLSConfig:         cfg,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       30 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       120 * time.Second,
	}
}

// HSTS adds Strict-Transport-Security so browsers stop trying plain HTTP.
func HSTS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
		next.ServeHTTP(w, r)
	})
}

The tests create a throwaway private CA, issue short-lived leaves, and verify: TLS 1.3 is negotiated, a TLS 1.1 client is refused, a name outside the SAN and an untrusted CA fail, a renewed certificate is served without a restart (and a broken renewal keeps the old one), and mTLS refuses a client without a certificate.

go
package tlsconfig

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"io"
	"math/big"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"testing"
	"time"
)

type ca struct {
	cert *x509.Certificate
	key  *ecdsa.PrivateKey
	pool *x509.CertPool
}

// newCA creates a throwaway private CA, the in-memory cousin of step-ca or
// Vault PKI.
func newCA(t *testing.T) ca {
	t.Helper()
	key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Test Root CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(time.Hour),
		IsCA:                  true,
		BasicConstraintsValid: true,
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		t.Fatal(err)
	}
	c, _ := x509.ParseCertificate(der)
	pool := x509.NewCertPool()
	pool.AddCert(c)
	return ca{cert: c, key: key, pool: pool}
}

// issue signs a short-lived leaf certificate. The SAN (DNSNames) is what
// clients verify; the Common Name is ignored by Go.
func (c ca) issue(t *testing.T, serial int64, dns string, usage x509.ExtKeyUsage) (certPEM, keyPEM []byte) {
	t.Helper()
	key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(serial),
		Subject:      pkix.Name{CommonName: dns},
		DNSNames:     []string{dns},
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(24 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{usage},
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, c.cert, &key.PublicKey, c.key)
	if err != nil {
		t.Fatal(err)
	}
	kb, _ := x509.MarshalECPrivateKey(key)
	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),
		pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kb})
}

func writePair(t *testing.T, dir string, certPEM, keyPEM []byte, mod time.Time) (string, string) {
	t.Helper()
	cf, kf := filepath.Join(dir, "tls.crt"), filepath.Join(dir, "tls.key")
	if err := os.WriteFile(kf, keyPEM, 0o600); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(cf, certPEM, 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.Chtimes(cf, mod, mod); err != nil {
		t.Fatal(err)
	}
	return cf, kf
}

func serve(t *testing.T, cfg *tls.Config) string {
	t.Helper()
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	srv := HTTPServer("", HSTS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "ok")
	})), cfg)
	go srv.Serve(tls.NewListener(ln, cfg))
	t.Cleanup(func() { srv.Close() })
	return ln.Addr().String()
}

func dial(addr string, cfg *tls.Config) (tls.ConnectionState, error) {
	conn, err := tls.Dial("tcp", addr, cfg)
	if err != nil {
		return tls.ConnectionState{}, err
	}
	defer conn.Close()
	return conn.ConnectionState(), nil
}

func TestModernServer(t *testing.T) {
	root := newCA(t)
	certPEM, keyPEM := root.issue(t, 10, "api.internal.example", x509.ExtKeyUsageServerAuth)
	cf, kf := writePair(t, t.TempDir(), certPEM, keyPEM, time.Now())
	r, err := NewReloader(cf, kf)
	if err != nil {
		t.Fatal(err)
	}
	addr := serve(t, Server(r.GetCertificate, nil))

	st, err := dial(addr, Client(root.pool, "api.internal.example"))
	if err != nil {
		t.Fatal(err)
	}
	if st.Version != tls.VersionTLS13 {
		t.Fatalf("negotiated %s, want TLS 1.3", tls.VersionName(st.Version))
	}

	old := Client(root.pool, "api.internal.example")
	old.MinVersion, old.MaxVersion = tls.VersionTLS10, tls.VersionTLS11
	if _, err := dial(addr, old); err == nil {
		t.Fatal("a TLS 1.1 client must be refused")
	}

	if _, err := dial(addr, Client(root.pool, "other.internal.example")); err == nil {
		t.Fatal("a name that is not in the SAN must fail verification")
	}
	if _, err := dial(addr, Client(x509.NewCertPool(), "api.internal.example")); err == nil {
		t.Fatal("an untrusted CA must fail verification")
	}
}

func TestCertificateHotReload(t *testing.T) {
	root := newCA(t)
	dir := t.TempDir()
	c1, k1 := root.issue(t, 100, "api.internal.example", x509.ExtKeyUsageServerAuth)
	cf, kf := writePair(t, dir, c1, k1, time.Now().Add(-time.Hour))
	r, err := NewReloader(cf, kf)
	if err != nil {
		t.Fatal(err)
	}
	addr := serve(t, Server(r.GetCertificate, nil))
	serial := func() int64 {
		cfg := Client(root.pool, "api.internal.example")
		cfg.SessionTicketsDisabled = true
		st, err := dial(addr, cfg)
		if err != nil {
			t.Fatal(err)
		}
		return st.PeerCertificates[0].SerialNumber.Int64()
	}
	if s := serial(); s != 100 {
		t.Fatalf("serial %d, want 100", s)
	}
	c2, k2 := root.issue(t, 200, "api.internal.example", x509.ExtKeyUsageServerAuth)
	writePair(t, dir, c2, k2, time.Now())
	if s := serial(); s != 200 {
		t.Fatalf("after renewal serial %d, want 200", s)
	}
	// A broken renewal keeps the last good certificate in service.
	os.WriteFile(cf, []byte("not a certificate"), 0o644)
	os.Chtimes(cf, time.Now().Add(time.Hour), time.Now().Add(time.Hour))
	if s := serial(); s != 200 {
		t.Fatalf("after broken renewal serial %d, want 200", s)
	}
}

func TestMutualTLS(t *testing.T) {
	root := newCA(t)
	sc, sk := root.issue(t, 1, "orders.internal.example", x509.ExtKeyUsageServerAuth)
	cf, kf := writePair(t, t.TempDir(), sc, sk, time.Now())
	r, _ := NewReloader(cf, kf)
	addr := serve(t, Server(r.GetCertificate, root.pool))

	// TLS 1.3 reports a missing client certificate after the handshake, on
	// the first read, so make a real HTTP request.
	get := func(cfg *tls.Config) error {
		c := &http.Client{Transport: &http.Transport{TLSClientConfig: cfg}, Timeout: 5 * time.Second}
		resp, err := c.Get("https://" + addr + "/")
		if err != nil {
			return err
		}
		resp.Body.Close()
		return nil
	}
	if err := get(Client(root.pool, "orders.internal.example")); err == nil {
		t.Fatal("a client without a certificate must be refused")
	}
	ccPEM, ckPEM := root.issue(t, 2, "payments.internal.example", x509.ExtKeyUsageClientAuth)
	pair, err := tls.X509KeyPair(ccPEM, ckPEM)
	if err != nil {
		t.Fatal(err)
	}
	cfg := Client(root.pool, "orders.internal.example")
	cfg.Certificates = []tls.Certificate{pair}
	if err := get(cfg); err != nil {
		t.Fatalf("client with a certificate: %v", err)
	}
}

secrets hides where a secret comes from: environment variables, mounted files (refusing world-readable ones and path traversal), Vault KV v2 and Vault dynamic database credentials with their lease, a Chain that does not fall back to a stale source on a hard error, and a TTL cache. The Secret type prints [REDACTED] through fmt, slog and JSON.

go
// Package secrets loads secrets from environment variables, mounted files
// or HashiCorp Vault behind one interface, so the application code never
// knows (or logs) where a secret came from.
package secrets

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"log/slog"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

var ErrNotFound = errors.New("secrets: not found")

// Secret wraps a value so that fmt, %v, %#v, JSON and slog print a
// placeholder instead of the value. Reveal is the only way out.
type Secret struct{ v string }

func New(v string) Secret                     { return Secret{v: v} }
func (s Secret) Reveal() string               { return s.v }
func (s Secret) String() string               { return "[REDACTED]" }
func (s Secret) GoString() string             { return "secrets.Secret{[REDACTED]}" }
func (s Secret) LogValue() slog.Value         { return slog.StringValue("[REDACTED]") }
func (s Secret) MarshalJSON() ([]byte, error) { return []byte(`"[REDACTED]"`), nil }

// Source looks up one secret by a logical name such as "db/password".
type Source interface {
	Lookup(ctx context.Context, name string) (Secret, error)
}

// Env maps "db/password" to PREFIX_DB_PASSWORD. Simple, and visible to every
// process that can read /proc/<pid>/environ, to crash dumps and to child
// processes: prefer File or Vault for anything long-lived.
type Env struct{ Prefix string }

func (e Env) Lookup(_ context.Context, name string) (Secret, error) {
	key := e.Prefix + strings.ToUpper(strings.NewReplacer("/", "_", "-", "_", ".", "_").Replace(name))
	v, ok := os.LookupEnv(key)
	if !ok || v == "" {
		return Secret{}, ErrNotFound
	}
	return New(v), nil
}

// File reads Dir/name, the layout of a Kubernetes Secret volume, Docker
// secrets (/run/secrets) or a Vault Agent / Secrets Store CSI mount. Files
// can be rotated in place and can carry 0400 permissions.
type File struct{ Dir string }

func (f File) Lookup(_ context.Context, name string) (Secret, error) {
	if !fs.ValidPath(name) {
		return Secret{}, fmt.Errorf("secrets: invalid name %q", name)
	}
	p := filepath.Join(f.Dir, filepath.FromSlash(name))
	st, err := os.Stat(p)
	if errors.Is(err, fs.ErrNotExist) {
		return Secret{}, ErrNotFound
	}
	if err != nil {
		return Secret{}, err
	}
	if st.Mode().Perm()&0o004 != 0 {
		return Secret{}, fmt.Errorf("secrets: %s is world-readable", p)
	}
	b, err := os.ReadFile(p)
	if err != nil {
		return Secret{}, err
	}
	return New(strings.TrimRight(string(b), "\r\n")), nil
}

// VaultKV reads KV version 2: GET {Addr}/v1/{Mount}/data/{path} with an
// X-Vault-Token header. "db/password" means path "db", field "password".
type VaultKV struct {
	Addr   string
	Mount  string
	Token  func(ctx context.Context) (string, error) // from Vault Agent, Kubernetes auth, AppRole...
	Client *http.Client
}

func (v VaultKV) Lookup(ctx context.Context, name string) (Secret, error) {
	i := strings.LastIndex(name, "/")
	if i <= 0 || i == len(name)-1 {
		return Secret{}, fmt.Errorf("secrets: vault name %q must be path/field", name)
	}
	var body struct {
		Data struct {
			Data     map[string]string `json:"data"`
			Metadata struct {
				Version int `json:"version"`
			} `json:"metadata"`
		} `json:"data"`
	}
	if err := v.get(ctx, "/v1/"+v.Mount+"/data/"+name[:i], &body); err != nil {
		return Secret{}, err
	}
	val, ok := body.Data.Data[name[i+1:]]
	if !ok {
		return Secret{}, ErrNotFound
	}
	return New(val), nil
}

// Lease is a dynamic database credential with its Vault lease.
type Lease struct {
	ID        string
	Duration  time.Duration
	Renewable bool
	Username  string
	Password  Secret
}

// DatabaseCreds asks the database secrets engine for a fresh, short-lived
// user: GET /v1/database/creds/{role}. Every caller gets its own user, so a
// leak is traceable and revoking the lease drops that one user.
func (v VaultKV) DatabaseCreds(ctx context.Context, role string) (Lease, error) {
	var body struct {
		LeaseID       string `json:"lease_id"`
		LeaseDuration int    `json:"lease_duration"`
		Renewable     bool   `json:"renewable"`
		Data          struct {
			Username string `json:"username"`
			Password string `json:"password"`
		} `json:"data"`
	}
	if err := v.get(ctx, "/v1/database/creds/"+role, &body); err != nil {
		return Lease{}, err
	}
	return Lease{
		ID: body.LeaseID, Duration: time.Duration(body.LeaseDuration) * time.Second,
		Renewable: body.Renewable, Username: body.Data.Username, Password: New(body.Data.Password),
	}, nil
}

func (v VaultKV) get(ctx context.Context, path string, out any) error {
	tok, err := v.Token(ctx)
	if err != nil {
		return fmt.Errorf("secrets: vault token: %w", err)
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(v.Addr, "/")+path, nil)
	if err != nil {
		return err
	}
	req.Header.Set("X-Vault-Token", tok)
	c := v.Client
	if c == nil {
		c = &http.Client{Timeout: 5 * time.Second}
	}
	resp, err := c.Do(req)
	if err != nil {
		return fmt.Errorf("secrets: vault: %w", err)
	}
	defer resp.Body.Close()
	switch {
	case resp.StatusCode == http.StatusNotFound:
		return ErrNotFound
	case resp.StatusCode != http.StatusOK:
		// Never include the response body: an error page may echo the request.
		return fmt.Errorf("secrets: vault %s: HTTP %d", path, resp.StatusCode)
	}
	return json.NewDecoder(resp.Body).Decode(out)
}

// Chain tries sources in order: for example File (production mount) then
// Env (local development). The first hit wins; errors other than
// ErrNotFound stop the search, so a Vault outage is not silently replaced
// by a stale environment variable.
type Chain []Source

func (c Chain) Lookup(ctx context.Context, name string) (Secret, error) {
	for _, s := range c {
		v, err := s.Lookup(ctx, name)
		if err == nil {
			return v, nil
		}
		if !errors.Is(err, ErrNotFound) {
			return Secret{}, err
		}
	}
	return Secret{}, fmt.Errorf("%w: %s", ErrNotFound, name)
}

// Cached keeps values for TTL so a hot path does not call Vault per request,
// and so a rotated secret is picked up within TTL without a restart.
type Cached struct {
	Source Source
	TTL    time.Duration
	Now    func() time.Time

	mu      sync.Mutex
	entries map[string]cacheEntry
}

type cacheEntry struct {
	v   Secret
	exp time.Time
}

func (c *Cached) Lookup(ctx context.Context, name string) (Secret, error) {
	now := time.Now
	if c.Now != nil {
		now = c.Now
	}
	c.mu.Lock()
	if e, ok := c.entries[name]; ok && now().Before(e.exp) {
		c.mu.Unlock()
		return e.v, nil
	}
	c.mu.Unlock()
	v, err := c.Source.Lookup(ctx, name)
	if err != nil {
		return Secret{}, err
	}
	c.mu.Lock()
	if c.entries == nil {
		c.entries = map[string]cacheEntry{}
	}
	c.entries[name] = cacheEntry{v: v, exp: now().Add(c.TTL)}
	c.mu.Unlock()
	return v, nil
}
go
package secrets

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestSecretNeverPrints(t *testing.T) {
	s := New("hunter2")
	var buf bytes.Buffer
	slog.New(slog.NewTextHandler(&buf, nil)).Info("connect", "password", s)
	js, _ := json.Marshal(map[string]any{"password": s})
	for _, out := range []string{fmt.Sprint(s), fmt.Sprintf("%v %+v %#v %s", s, s, s, s), buf.String(), string(js)} {
		if strings.Contains(out, "hunter2") {
			t.Fatalf("secret leaked: %s", out)
		}
	}
	if s.Reveal() != "hunter2" {
		t.Fatal("Reveal must return the value")
	}
}

func TestEnv(t *testing.T) {
	t.Setenv("APP_DB_PASSWORD", "from-env")
	v, err := Env{Prefix: "APP_"}.Lookup(context.Background(), "db/password")
	if err != nil || v.Reveal() != "from-env" {
		t.Fatalf("%v %v", v.Reveal(), err)
	}
}

func TestFile(t *testing.T) {
	dir := t.TempDir()
	os.MkdirAll(filepath.Join(dir, "db"), 0o700)
	os.WriteFile(filepath.Join(dir, "db", "password"), []byte("from-file\n"), 0o400)
	f := File{Dir: dir}
	v, err := f.Lookup(context.Background(), "db/password")
	if err != nil || v.Reveal() != "from-file" {
		t.Fatalf("%q %v", v.Reveal(), err)
	}
	if _, err := f.Lookup(context.Background(), "../etc/passwd"); err == nil || errors.Is(err, ErrNotFound) {
		t.Fatalf("path traversal must be an error, got %v", err)
	}
	os.WriteFile(filepath.Join(dir, "open"), []byte("x"), 0o644)
	if _, err := f.Lookup(context.Background(), "open"); err == nil {
		t.Fatal("a world-readable secret file must be refused")
	}
}

func fakeVault(t *testing.T, calls *int) *httptest.Server {
	t.Helper()
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		*calls++
		if r.Header.Get("X-Vault-Token") != "s.test" {
			http.Error(w, `{"errors":["permission denied"]}`, http.StatusForbidden)
			return
		}
		switch r.URL.Path {
		case "/v1/secret/data/payments":
			body := `{"data":{"data":{"stripe_key":"sk_test_123"},"metadata":{"version":3}}}`
			w.Write([]byte(body))
		case "/v1/database/creds/orders-rw":
			w.Write([]byte(`{"lease_id":"database/creds/orders-rw/abc","lease_duration":3600,"renewable":true,
			  "data":{"username":"v-orders-rw-x1","password":"p-123"}}`))
		default:
			http.NotFound(w, r)
		}
	}))
}

func TestVaultKVAndDynamicCreds(t *testing.T) {
	calls := 0
	srv := fakeVault(t, &calls)
	defer srv.Close()
	tok := func(context.Context) (string, error) { return "s.test", nil }
	v := VaultKV{Addr: srv.URL, Mount: "secret", Token: tok}
	ctx := context.Background()

	s, err := v.Lookup(ctx, "payments/stripe_key")
	if err != nil || s.Reveal() != "sk_test_123" {
		t.Fatalf("%v %v", s.Reveal(), err)
	}
	if _, err := v.Lookup(ctx, "payments/missing"); !errors.Is(err, ErrNotFound) {
		t.Fatalf("missing field: %v", err)
	}
	if _, err := v.Lookup(ctx, "nothing/here"); !errors.Is(err, ErrNotFound) {
		t.Fatalf("missing path: %v", err)
	}
	lease, err := v.DatabaseCreds(ctx, "orders-rw")
	if err != nil || lease.Duration != time.Hour || !lease.Renewable || lease.Username != "v-orders-rw-x1" {
		t.Fatalf("%+v %v", lease, err)
	}
	bad := VaultKV{Addr: srv.URL, Mount: "secret", Token: func(context.Context) (string, error) { return "wrong", nil }}
	if _, err := bad.Lookup(ctx, "payments/stripe_key"); err == nil || errors.Is(err, ErrNotFound) {
		t.Fatalf("403 must be a hard error, got %v", err)
	}
}

func TestChainStopsOnHardError(t *testing.T) {
	t.Setenv("APP_PAYMENTS_STRIPE_KEY", "stale-env-value")
	calls := 0
	srv := fakeVault(t, &calls)
	defer srv.Close()
	down := VaultKV{Addr: srv.URL, Mount: "secret", Token: func(context.Context) (string, error) { return "", errors.New("agent not ready") }}
	c := Chain{down, Env{Prefix: "APP_"}}
	if _, err := c.Lookup(context.Background(), "payments/stripe_key"); err == nil {
		t.Fatal("a Vault failure must not fall back to a stale env var")
	}
	ok := Chain{File{Dir: t.TempDir()}, Env{Prefix: "APP_"}}
	if v, err := ok.Lookup(context.Background(), "payments/stripe_key"); err != nil || v.Reveal() != "stale-env-value" {
		t.Fatalf("not-found must fall through: %v", err)
	}
}

func TestCachedTTL(t *testing.T) {
	calls := 0
	srv := fakeVault(t, &calls)
	defer srv.Close()
	now := time.Unix(0, 0)
	c := &Cached{
		Source: VaultKV{Addr: srv.URL, Mount: "secret", Token: func(context.Context) (string, error) { return "s.test", nil }},
		TTL:    time.Minute,
		Now:    func() time.Time { return now },
	}
	for i := 0; i < 5; i++ {
		c.Lookup(context.Background(), "payments/stripe_key")
	}
	if calls != 1 {
		t.Fatalf("5 lookups inside the TTL made %d Vault calls, want 1", calls)
	}
	now = now.Add(61 * time.Second)
	c.Lookup(context.Background(), "payments/stripe_key")
	if calls != 2 {
		t.Fatalf("after TTL calls = %d, want 2", calls)
	}
}

Finally, the nonce arithmetic used throughout the page.

go
// Command noncemath prints the probability that random nonces collide under
// one key (the birthday bound) for 96-bit nonces (AES-GCM, ChaCha20-Poly1305)
// and 192-bit nonces (XChaCha20-Poly1305), and how long a service takes to
// reach NIST SP 800-38D's 2^32 limit for random 96-bit IVs.
package main

import (
	"fmt"
	"math"
)

// collision returns 1 - exp(-n(n-1)/2^(bits+1)), computed with Expm1 so tiny
// probabilities do not round to zero.
func collision(n float64, bits int) float64 {
	return -math.Expm1(-n * (n - 1) / math.Pow(2, float64(bits+1)))
}

func main() {
	fmt.Printf("%-8s %-16s %-14s %-14s\n", "msgs", "count", "p(96-bit)", "p(192-bit)")
	for _, e := range []int{20, 28, 32, 36, 40, 48} {
		n := math.Pow(2, float64(e))
		fmt.Printf("2^%-6d %-16.0f %-14.3g %-14.3g\n", e, n, collision(n, 96), collision(n, 192))
	}
	fmt.Println()
	limit := math.Pow(2, 32)
	for _, rate := range []float64{100, 10_000, 1_000_000} {
		hours := limit / rate / 3600
		fmt.Printf("one key at %9.0f encryptions/s reaches 2^32 in %9.1f hours (%.1f days)\n", rate, hours, hours/24)
	}
}

The Go angle ​

Go's standard library covers almost everything on this page without dependencies: crypto/cipher (GCM), crypto/hkdf and crypto/hmac, crypto/ecdh (X25519, P-256), crypto/ed25519, crypto/x509 and crypto/tls, and crypto/rand. ChaCha20-Poly1305 and XChaCha20-Poly1305 (chacha20poly1305.NewX) and Argon2 live in golang.org/x/crypto. Three Go-specific facts matter for system design. First, crypto/tls deliberately does not let you configure TLS 1.3 suites and ships good defaults (TLS 1.2 minimum, X25519MLKEM768 in the default key exchanges since Go 1.24), so the main risk is code that weakens them (InsecureSkipVerify: true). Second, crypto/rand.Read never returns an error and crashes the program if the OS generator fails, so there is no error path to get wrong. Third, the Go Cryptographic Module can run in FIPS 140-3 mode (GOFIPS140 at build time or GODEBUG=fips140=on), in which crypto/tls "will ignore and not negotiate any protocol version, cipher suite, signature algorithm, or key exchange mechanism that is not FIPS 140-3 approved". Real KMS clients (aws-sdk-go-v2/service/kms, cloud.google.com/go/kms, github.com/hashicorp/vault/api) implement the same Wrapper shape; for production envelope encryption prefer Google Tink or the AWS Encryption SDK over the teaching code here. clear(dek) is best effort: Go may have copied the slice, and the garbage collector does not zero memory.

Laravel ​

Before ​

The first version stores a card number in plaintext with an MD5 "lookup hash", reads an API key with env() outside configuration (which returns null after config:cache) with a committed fallback, and builds reset tokens from mt_rand and uniqid.

php
<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

// Works on day one, fails an audit on day two. Every PROBLEM is a design flaw.
class PaymentSettings
{
    public function saveCard(int $userId, string $cardNumber): void
    {
        DB::table('cards')->insert([
            'user_id' => $userId,
            // PROBLEM 1: the card number is stored in plaintext. Disk
            // encryption and TDE do not help against SQL injection, a leaked
            // backup restored elsewhere, or a support tool that runs SELECT *.
            'number' => $cardNumber,
            // PROBLEM 2: MD5 is not a lookup key for sensitive data: the
            // 10^16 card space is brute-forced offline in hours.
            'number_hash' => md5($cardNumber),
        ]);
    }

    public function gatewayKey(): string
    {
        // PROBLEM 3: env() outside config files returns null after
        // `php artisan config:cache`, because .env is no longer loaded.
        // PROBLEM 4: the fallback is a real key committed to git.
        return env('PAYMENT_GATEWAY_KEY', 'sk_live_51H...committed-to-git');
    }

    public function resetToken(): string
    {
        // PROBLEM 5: mt_rand() and uniqid() are predictable. Use
        // random_bytes() or Str::random(), which uses random_bytes().
        return md5(uniqid((string) mt_rand(), true));
    }
}

After ​

Laravel's encrypter uses APP_KEY and accepts old keys for decryption from APP_PREVIOUS_KEYS, as in the skeleton's config/app.php:

php
<?php

// Excerpt of config/app.php in the Laravel 13 application skeleton.
// APP_KEY is the current key; APP_PREVIOUS_KEYS is a comma-separated list
// of old keys that are still accepted for decryption only.
return [
    'cipher' => 'AES-256-CBC', // Laravel also supports AES-128-CBC, AES-128-GCM, AES-256-GCM

    'key' => env('APP_KEY'),

    'previous_keys' => [
        ...array_filter(
            explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
        ),
    ],
];

Encrypted casts keep sensitive columns unreadable in the database; a blind index (HKDF-derived HMAC key, separate from APP_KEY) allows exact-match lookup.

php
<?php

namespace App\Models;

use App\Crypto\BlindIndex;
use Illuminate\Database\Eloquent\Casts\AsEncryptedArrayObject;
use Illuminate\Database\Eloquent\Model;

class Patient extends Model
{
    protected $fillable = ['name', 'national_id', 'diagnosis', 'contacts'];

    // The column stays readable to Eloquent and unreadable to anyone with
    // only the database: SQL injection dumps, backups, replicas, analysts.
    protected function casts(): array
    {
        return [
            'national_id' => 'encrypted',          // TEXT column: ciphertext is longer and variable
            'diagnosis' => 'encrypted',
            'contacts' => AsEncryptedArrayObject::class,
        ];
    }

    // Encrypted casts cannot be searched. A blind index (keyed HMAC of the
    // normalized value) allows exact-match lookups and nothing else.
    protected static function booted(): void
    {
        static::saving(function (Patient $patient): void {
            if ($patient->isDirty('national_id')) {
                $patient->national_id_bidx = BlindIndex::for('patients.national_id', (string) $patient->national_id);
            }
        });
    }

    public static function findByNationalId(string $nationalId): ?self
    {
        return static::where('national_id_bidx', BlindIndex::for('patients.national_id', $nationalId))->first();
    }
}
php
<?php

namespace App\Crypto;

use RuntimeException;

final class BlindIndex
{
    // HMAC-SHA-256 under a key derived with HKDF for this one column. The
    // root key is BLIND_INDEX_KEY (32 random bytes, base64), NOT APP_KEY:
    // rotating APP_KEY must not invalidate every index.
    public static function for(string $column, string $value): string
    {
        $root = base64_decode((string) config('services.blind_index.key'), true);
        if ($root === false || strlen($root) !== 32) {
            throw new RuntimeException('services.blind_index.key must be 32 random bytes, base64 encoded');
        }
        $key = hash_hkdf('sha256', $root, 32, 'blind-index/'.$column.'/v1');
        $normalized = mb_strtolower(trim($value));

        return substr(hash_hmac('sha256', $normalized, $key, true), 0, 16);
    }
}
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('patients', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('national_id');                       // encrypted cast: TEXT, never VARCHAR(20)
            $table->binary('national_id_bidx', length: 16, fixed: true)->unique(); // blind index
            $table->text('diagnosis')->nullable();
            $table->text('contacts')->nullable();
            $table->timestamps();
        });

        Schema::create('patient_notes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->index();
            $table->text('body_envelope');                     // env1:... (wrapped DEK + IV + tag + ciphertext)
            $table->string('kek_id')->index();                 // which KMS key wrapped the DEK: drives rewrap jobs
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('patient_notes');
        Schema::dropIfExists('patients');
    }
};

For data that needs per-tenant keys, rotation without re-encryption and crypto-shredding, an envelope encrypter uses AWS KMS through the AWS SDK for PHP (generateDataKey, decrypt, reEncrypt) behind a small interface, and AES-256-GCM through openssl_encrypt locally.

php
<?php

namespace App\Crypto;

final class DataKey
{
    public function __construct(
        #[\SensitiveParameter] public readonly string $plaintext, // 32 bytes, never stored
        public readonly string $wrapped,                           // KMS CiphertextBlob, stored
        public readonly string $keyId,                             // KEK ARN or name, stored
    ) {}
}
php
<?php

namespace App\Crypto;

interface DataKeyProvider
{
    /** @param array<string, string> $context */
    public function generate(array $context): DataKey;

    /** @param array<string, string> $context */
    public function unwrap(string $wrapped, array $context): string;

    /** @param array<string, string> $context */
    public function rewrap(string $wrapped, array $context, string $destinationKeyId): string;
}
php
<?php

namespace App\Crypto;

use Aws\Kms\KmsClient;

// AWS SDK for PHP v3 (composer require aws/aws-sdk-php). The KMS key never
// leaves AWS KMS; only 32-byte data keys travel, over TLS.
final class AwsKmsDataKeyProvider implements DataKeyProvider
{
    public function __construct(
        private readonly KmsClient $kms,
        private readonly string $keyId, // alias/app-pii or a key ARN
    ) {}

    public function generate(array $context): DataKey
    {
        $result = $this->kms->generateDataKey([
            'KeyId' => $this->keyId,
            'KeySpec' => 'AES_256',
            // Encryption context: logged in CloudTrail, required again on Decrypt.
            'EncryptionContext' => $context,
        ]);

        return new DataKey($result['Plaintext'], $result['CiphertextBlob'], $result['KeyId']);
    }

    public function unwrap(string $wrapped, array $context): string
    {
        return $this->kms->decrypt([
            'CiphertextBlob' => $wrapped,
            'EncryptionContext' => $context,
            'KeyId' => $this->keyId, // refuse blobs wrapped by any other key
        ])['Plaintext'];
    }

    public function rewrap(string $wrapped, array $context, string $destinationKeyId): string
    {
        // ReEncrypt runs inside AWS KMS: the data key is never exposed here.
        return $this->kms->reEncrypt([
            'CiphertextBlob' => $wrapped,
            'SourceEncryptionContext' => $context,
            'DestinationKeyId' => $destinationKeyId,
            'DestinationEncryptionContext' => $context,
        ])['CiphertextBlob'];
    }
}
php
<?php

namespace App\Crypto;

use RuntimeException;

// Envelope encryption with AES-256-GCM: one fresh data key per value, the
// data key wrapped by the KMS, the context bound as associated data.
final class EnvelopeEncrypter
{
    private const CIPHER = 'aes-256-gcm';

    public function __construct(private readonly DataKeyProvider $keys) {}

    /** @param array<string, string> $context e.g. ['table' => 'patients', 'column' => 'notes', 'id' => '42'] */
    public function encrypt(#[\SensitiveParameter] string $plaintext, array $context): string
    {
        $dataKey = $this->keys->generate($context);
        $iv = random_bytes(12); // one value per data key: a random 96-bit IV cannot repeat
        $tag = '';
        $ciphertext = openssl_encrypt($plaintext, self::CIPHER, $dataKey->plaintext, OPENSSL_RAW_DATA, $iv, $tag, $this->aad($context), 16);
        if ($ciphertext === false) {
            throw new RuntimeException('Encryption failed.');
        }

        return 'env1:'.base64_encode(json_encode([
            'kid' => $dataKey->keyId,
            'wdek' => base64_encode($dataKey->wrapped),
            'iv' => base64_encode($iv),
            'tag' => base64_encode($tag),
            'ct' => base64_encode($ciphertext),
        ], JSON_THROW_ON_ERROR));
    }

    /** @param array<string, string> $context */
    public function decrypt(string $envelope, array $context): string
    {
        $e = $this->parse($envelope);
        $key = $this->keys->unwrap($e['wdek'], $context);
        $plaintext = openssl_decrypt($e['ct'], self::CIPHER, $key, OPENSSL_RAW_DATA, $e['iv'], $e['tag'], $this->aad($context));
        if ($plaintext === false) {
            throw new RuntimeException('Decryption failed: wrong context or tampered value.');
        }

        return $plaintext;
    }

    /** @param array<string, string> $context */
    public function rewrap(string $envelope, array $context, string $destinationKeyId): string
    {
        $e = $this->parse($envelope);
        $wrapped = $this->keys->rewrap($e['wdek'], $context, $destinationKeyId);

        return 'env1:'.base64_encode(json_encode([
            'kid' => $destinationKeyId,
            'wdek' => base64_encode($wrapped),
            'iv' => base64_encode($e['iv']),
            'tag' => base64_encode($e['tag']),
            'ct' => base64_encode($e['ct']),
        ], JSON_THROW_ON_ERROR));
    }

    public function keyIdOf(string $envelope): string
    {
        return $this->parse($envelope)['kid'];
    }

    /** @return array{kid: string, wdek: string, iv: string, tag: string, ct: string} */
    private function parse(string $envelope): array
    {
        if (! str_starts_with($envelope, 'env1:')) {
            throw new RuntimeException('Unknown envelope format.');
        }
        $data = json_decode((string) base64_decode(substr($envelope, 5), true), true, 4, JSON_THROW_ON_ERROR);
        foreach (['kid', 'wdek', 'iv', 'tag', 'ct'] as $field) {
            if (! isset($data[$field]) || ! is_string($data[$field])) {
                throw new RuntimeException("Malformed envelope: {$field}.");
            }
        }

        return [
            'kid' => $data['kid'],
            'wdek' => (string) base64_decode($data['wdek'], true),
            'iv' => (string) base64_decode($data['iv'], true),
            'tag' => (string) base64_decode($data['tag'], true),
            'ct' => (string) base64_decode($data['ct'], true),
        ];
    }

    /** @param array<string, string> $context */
    private function aad(array $context): string
    {
        ksort($context);

        return json_encode($context, JSON_THROW_ON_ERROR);
    }
}
php
<?php

namespace App\Providers;

use App\Crypto\AwsKmsDataKeyProvider;
use App\Crypto\DataKeyProvider;
use Aws\Kms\KmsClient;
use Illuminate\Support\ServiceProvider;

class CryptoServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(DataKeyProvider::class, function () {
            // No access keys in config: the SDK picks up the IAM role of the
            // instance, the ECS task or the EKS pod (IRSA / Pod Identity).
            $client = new KmsClient([
                'version' => '2014-11-01',
                'region' => config('services.kms.region'),
            ]);

            return new AwsKmsDataKeyProvider($client, (string) config('services.kms.key_id'));
        });
    }
}

Two commands make rotation routine: re-encrypting encrypted-cast columns after an APP_KEY rotation, and rewrapping data keys to a new KMS key.

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

// After moving the old key into APP_PREVIOUS_KEYS and setting a new APP_KEY,
// old values still decrypt, but they stay under the old key until rewritten.
// This command rewrites them so the old key can finally be removed.
class ReencryptAfterKeyRotation extends Command
{
    protected $signature = 'crypto:reencrypt {table} {columns*} {--chunk=500}';

    protected $description = 'Re-encrypt encrypted-cast columns with the current APP_KEY';

    public function handle(): int
    {
        $table = $this->argument('table');
        $columns = $this->argument('columns');
        // An encrypter with ONLY the current key: if it can decrypt a value,
        // the value is already up to date and is skipped.
        $currentOnly = new Encrypter(Crypt::getKey(), config('app.cipher'));
        $rewritten = 0;

        DB::table($table)->select(['id', ...$columns])->orderBy('id')
            ->chunkById((int) $this->option('chunk'), function ($rows) use ($table, $columns, $currentOnly, &$rewritten) {
                foreach ($rows as $row) {
                    $changes = [];
                    foreach ($columns as $column) {
                        $raw = $row->{$column};
                        if ($raw === null) {
                            continue;
                        }
                        try {
                            $currentOnly->decryptString($raw);
                            continue; // already under the current key
                        } catch (DecryptException) {
                            // Crypt tries APP_KEY, then every APP_PREVIOUS_KEYS entry.
                            $changes[$column] = Crypt::encryptString(Crypt::decryptString($raw));
                        }
                    }
                    if ($changes !== []) {
                        DB::table($table)->where('id', $row->id)->update($changes);
                        $rewritten++;
                    }
                }
            });

        $this->info("Rewrote {$rewritten} rows in {$table}. Remove the old key from APP_PREVIOUS_KEYS only after every table reports 0.");

        return self::SUCCESS;
    }
}
php
<?php

namespace App\Console\Commands;

use App\Crypto\EnvelopeEncrypter;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

// Moves every wrapped data key from one KMS key to another (new key, new
// region, new account) without decrypting a single record. AWS KMS
// automatic rotation does NOT need this: it keeps old key material.
class RewrapDataKeys extends Command
{
    protected $signature = 'crypto:rewrap {destinationKeyId} {--chunk=200}';

    protected $description = 'Re-wrap envelope-encrypted patient notes under another KMS key';

    public function handle(EnvelopeEncrypter $envelopes): int
    {
        $destination = $this->argument('destinationKeyId');
        $moved = 0;

        DB::table('patient_notes')->select(['id', 'tenant_id', 'body_envelope'])->orderBy('id')
            ->chunkById((int) $this->option('chunk'), function ($rows) use ($envelopes, $destination, &$moved) {
                foreach ($rows as $row) {
                    if ($envelopes->keyIdOf($row->body_envelope) === $destination) {
                        continue; // idempotent: safe to rerun after a crash
                    }
                    $context = ['table' => 'patient_notes', 'id' => (string) $row->id, 'tenant' => (string) $row->tenant_id];
                    DB::table('patient_notes')->where('id', $row->id)->update([
                        'body_envelope' => $envelopes->rewrap($row->body_envelope, $context, $destination),
                        'kek_id' => $destination,
                    ]);
                    $moved++;
                }
            });

        $this->info("Re-wrapped {$moved} data keys.");

        return self::SUCCESS;
    }
}

Secrets come from the environment or from files (NAME_FILE), read only inside configuration files so they survive config:cache:

php
<?php

namespace App\Support;

final class SecretFile
{
    // Reads NAME from the environment, or the file named by NAME_FILE (the
    // Docker secrets / Kubernetes volume convention). Called from config
    // files only. Caveat: `php artisan config:cache` writes the resolved
    // value into bootstrap/cache/config.php in plaintext, so that file must
    // be treated as a secret (0600, never in an image layer or an artifact).
    public static function env(string $name, ?string $default = null): ?string
    {
        $value = env($name);
        if (is_string($value) && $value !== '') {
            return $value;
        }
        $file = env($name.'_FILE');
        if (is_string($file) && is_readable($file)) {
            return rtrim((string) file_get_contents($file), "\r\n");
        }

        return $default;
    }
}
php
<?php

use App\Support\SecretFile;

// Excerpt of config/services.php and config/database.php.
return [
    'kms' => [
        'region' => env('AWS_DEFAULT_REGION', 'eu-central-1'),
        'key_id' => env('KMS_PII_KEY_ID', 'alias/app-pii'),
    ],

    'blind_index' => [
        'key' => SecretFile::env('BLIND_INDEX_KEY'),
    ],

    'mysql_password' => SecretFile::env('DB_PASSWORD'), // DB_PASSWORD or DB_PASSWORD_FILE=/run/secrets/db_password
];

At deploy time, Vault Agent renders the environment from Vault before the cache is built, so no secret is ever in git or in the image:

bash
# vault-agent template (agent.hcl excerpt) renders /app/.env from Vault KV v2
#   template { source = "/etc/vault/env.ctmpl"  destination = "/app/.env"  perms = "0600" }
# env.ctmpl:
#   DB_PASSWORD={{ with secret "secret/data/orders/db" }}{{ .Data.data.password }}{{ end }}
php artisan config:cache   # bakes resolved values into bootstrap/cache/config.php (treat it as a secret)
php artisan optimize

The feature tests use a fake KMS provider and the framework's Encrypter directly.

php
<?php

namespace Tests\Fakes;

use App\Crypto\DataKey;
use App\Crypto\DataKeyProvider;
use RuntimeException;

// In-memory stand-in for AWS KMS: one AES-256-GCM KEK per key id.
final class FakeDataKeyProvider implements DataKeyProvider
{
    /** @var array<string, string> */
    private array $keks = [];

    public int $calls = 0;

    public function __construct(private string $keyId = 'alias/test') {}

    public function generate(array $context): DataKey
    {
        $dek = random_bytes(32);

        return new DataKey($dek, $this->wrap($this->keyId, $dek, $context), $this->keyId);
    }

    public function unwrap(string $wrapped, array $context): string
    {
        $this->calls++;
        [$keyId, $iv, $tag, $ct] = explode('|', $wrapped);
        $dek = openssl_decrypt(base64_decode($ct), 'aes-256-gcm', $this->kek($keyId), OPENSSL_RAW_DATA, base64_decode($iv), base64_decode($tag), $this->aad($context));
        if ($dek === false) {
            throw new RuntimeException('InvalidCiphertextException');
        }

        return $dek;
    }

    public function rewrap(string $wrapped, array $context, string $destinationKeyId): string
    {
        return $this->wrap($destinationKeyId, $this->unwrap($wrapped, $context), $context);
    }

    private function wrap(string $keyId, string $dek, array $context): string
    {
        $this->calls++;
        $iv = random_bytes(12);
        $tag = '';
        $ct = openssl_encrypt($dek, 'aes-256-gcm', $this->kek($keyId), OPENSSL_RAW_DATA, $iv, $tag, $this->aad($context), 16);

        return implode('|', [$keyId, base64_encode($iv), base64_encode($tag), base64_encode((string) $ct)]);
    }

    private function kek(string $keyId): string
    {
        return $this->keks[$keyId] ??= random_bytes(32);
    }

    private function aad(array $context): string
    {
        ksort($context);

        return json_encode($context, JSON_THROW_ON_ERROR);
    }
}
php
<?php

namespace Tests\Feature;

use App\Crypto\EnvelopeEncrypter;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Encryption\Encrypter;
use RuntimeException;
use Tests\Fakes\FakeDataKeyProvider;
use Tests\TestCase;

class EncryptionTest extends TestCase
{
    private array $context = ['table' => 'patient_notes', 'id' => '42', 'tenant' => '7'];

    public function test_envelope_round_trip_and_fresh_data_key(): void
    {
        $envelopes = new EnvelopeEncrypter(new FakeDataKeyProvider);
        $a = $envelopes->encrypt('allergic to penicillin', $this->context);
        $b = $envelopes->encrypt('allergic to penicillin', $this->context);

        $this->assertNotSame($a, $b);
        $this->assertSame('allergic to penicillin', $envelopes->decrypt($a, $this->context));
    }

    public function test_context_is_bound_to_the_row(): void
    {
        $envelopes = new EnvelopeEncrypter(new FakeDataKeyProvider);
        $blob = $envelopes->encrypt('secret', $this->context);

        $this->expectException(RuntimeException::class);
        $envelopes->decrypt($blob, [...$this->context, 'id' => '43']);
    }

    public function test_rewrap_keeps_the_ciphertext_readable(): void
    {
        $envelopes = new EnvelopeEncrypter(new FakeDataKeyProvider('alias/old'));
        $blob = $envelopes->encrypt('note', $this->context);
        $moved = $envelopes->rewrap($blob, $this->context, 'alias/new');

        $this->assertSame('alias/new', $envelopes->keyIdOf($moved));
        $this->assertSame('note', $envelopes->decrypt($moved, $this->context));
    }

    public function test_app_key_rotation_with_previous_keys(): void
    {
        $old = Encrypter::generateKey('aes-256-cbc');
        $new = Encrypter::generateKey('aes-256-cbc');
        $value = (new Encrypter($old, 'aes-256-cbc'))->encryptString('078-05-1120');

        $rotated = (new Encrypter($new, 'aes-256-cbc'))->previousKeys([$old]);
        $this->assertSame('078-05-1120', $rotated->decryptString($value));

        $this->expectException(DecryptException::class);
        (new Encrypter($new, 'aes-256-cbc'))->decryptString($value);
    }
}

The Laravel angle ​

Laravel gives three cryptographic tools out of the box. Crypt / encrypt(): "All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC)"; the framework's Encrypter also supports aes-128-gcm and aes-256-gcm, and every cookie, including the session cookie, is encrypted with it. Key rotation: "Laravel will always use the 'current' encryption key when encrypting values. However, when decrypting values, Laravel will first try the current key, and if decryption fails using the current key, Laravel will try all previous keys". Encrypted casts (encrypted, encrypted:array, encrypted:collection, encrypted:object, AsEncryptedArrayObject, AsEncryptedCollection) need TEXT columns and cannot be searched. The limits: APP_KEY is one key for the whole application (cookies, sessions, casts), so it is a single-level hierarchy with no per-tenant keys and no crypto-shredding, and old values stay under the old key until rewritten (the crypto:reencrypt command). For anything beyond that, use envelope encryption with a KMS as above. On secrets: php artisan config:cache stops loading .env, so "the env function will only return external, system level environment variables"; call env() only inside config/*.php. php artisan env:encrypt encrypts .env into .env.encrypted (AES-256-CBC by default) with a key you must store elsewhere; it is useful for small teams and still means the decryption key must be injected at deploy. Hashing passwords is a different tool (Hash::make, argon2id driver), covered in Authentication.

Solving the classic problems ​

A key was committed to git ​

SolutionHowAdvantageCost
Revoke and rotate firstDeactivate at the provider, issue a new key, deployEnds the exposureRequires a rotation path you have practised
InvestigateProvider access logs (CloudTrail, Stripe logs) for the exposure windowKnow what was doneTime
Clean historygit filter-repo, force push, ask forks to deleteStops future rediscoveryDoes not remove existing clones
Preventgitleaks pre-commit, push protection, TruffleHog in CIBlocks the next oneFalse positives to triage

Rotating Laravel's APP_KEY without logging everyone out ​

StepActionEffect
1Move the current key to APP_PREVIOUS_KEYS, set a new APP_KEY (php artisan key:generate --show), deploy, config:cacheNew values use the new key; sessions and old values still decrypt
2Run php artisan crypto:reencrypt patients national_id diagnosis contacts per tableValues move to the new key
3Wait one session lifetimeOld session cookies expire naturally
4Remove the old key from APP_PREVIOUS_KEYSThe old key is retired

A certificate expired in production ​

SolutionHowAdvantageCost
Automate renewalcert-manager, Caddy, certbot timers, AWS ACM managed renewalNo human in the loopMust monitor the automation itself
Monitor from outsideBlackbox exporter probe_ssl_earliest_cert_expiry, synthetic checksCatches the forgotten load balancerOne more alert
Hot reloadGetCertificate reloader, NGINX reload, Envoy SDSRenewal without restartsCode or config per server
InventoryCT logs for public names, CA issuance logs for private onesFinds certificates nobody ownsProcess

Nonce reuse or too many messages under one key ​

SolutionHowAdvantageCost
DEK per record or objectEnvelope encryptionLimit never bindsKMS calls (cache them)
XChaCha20-Poly1305192-bit random noncesSafe random nonces at volumeNot FIPS approved
AES-GCM-SIVMisuse-resistant AEADRepeated nonce leaks only equalityTwo passes over the data; fewer libraries
Count and rotateEncryption counter per key, rotate before 2^32Works with plain GCMState to keep correct across replicas

Erasing one customer from immutable storage ​

SolutionHowAdvantageCost
Crypto-shreddingPer-subject or per-tenant key, destroy itCovers backups, replicas, logsKey granularity designed up front
Tombstone + compactionKafka compacted topics, delete markersNative for keyed topicsDoes not reach backups
Backup expiryErasure completes when the last backup ages outSimpleWeeks to months of delay

KMS latency, cost and quotas ​

SolutionHowAdvantageCost
Data-key cachingAWS Encryption SDK caching CMM, Tink, local LRU with TTL and use limitsOrders of magnitude fewer KMS callsPlaintext keys in memory longer
One DEK per object, not per fieldEncrypt a JSON document as a unitFewer keysCoarser access control
Batch rewrap off-peakChunked jobs with rate limitsAvoids throttlingSlower rotation
Multi-region keysAWS KMS multi-region keys, Cloud KMS multi-region locationsLocal latency, DRKey policy replicated across regions

A compromised intermediate CA or signing key ​

SolutionHowAdvantageCost
Two-tier PKIOffline root signs a new intermediateRoot survivesRoot ceremony
Short leaf lifetimesLeaves from the old intermediate expire in hours or daysNo revocation neededAutomation required
Trust bundle rolloverDistribute the new intermediate or root before switchingNo outagePlanning
TransparencyCT monitoring, Rekor for signaturesDetects misuseMonitoring effort

Choosing ​

What to encrypt, where ​

Data / situationLayerKey designReason
Every disk, volume, snapshot, bucketDisk / SSE-KMSProvider default keys or CMKFree baseline against media loss
Card numbers, national ids, health notesField-level envelopePer-tenant KEK in KMS, DEK per value, blind index if lookupsStops injection, dumps, analysts
Free-text personal data in an event storeField-level, per subjectPer-subject keys wrapped by tenant KEKCrypto-shredding for erasure
Session cookies, signed URLsFramework encrypter / HMACAPP_KEY, rotated with previous keysBuilt in, short-lived
PasswordsNot encryption: hashingArgon2idMust not be reversible
Search fields (name, address)Disk + access controln/aField encryption kills search; reduce access instead
Backups shipped to another account/regionBackup encryption with a separate KEKKEK in the destination regionIsolates blast radius
Messages in Kafka with long retentionPayload envelope encryptionKEK per data classBrokers and consumers without the key see ciphertext

Which certificate source ​

EndpointSourceLifetimeRenewal
Public website / APILet's Encrypt or a commercial CA via ACME, or AWS ACM90 days now, 47 by 2029cert-manager, Caddy, certbot, ACM
Origin behind a CDNCDN origin CA or public CALong for origin CA (CDN-specific)Provider
Internal HTTP/gRPC between servicesMesh CA (Istio, Linkerd) or SPIREHoursAutomatic
Databases, brokersPrivate CA (step-ca, Vault PKI, AWS Private CA)Days to monthsAgent or cert-manager
Developer laptopsmkcert (see TLS in Practice)LongManual, never in production

Which secret store and injection ​

SituationStoreInjectionRotation
AWS-only, RDS databasesAWS Secrets ManagerECS secrets / ESO / SDKManaged rotation
Multi-cloud, dynamic database usersVaultVault Agent sidecarLeases
Kubernetes with GitOpsVault or a cloud store + ESO; or SOPS/age, sealed-secretsFilesStore-driven or re-seal
Small Laravel app on one VMCloud secret store or env:encryptRendered .env at deploy, config:cacheManual, scheduled
CI/CD access to cloudsNo stored secret: OIDC federationShort-lived tokensAutomatic

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel or Go monolith needs four things, in this order: TLS at the edge (a managed certificate on the load balancer or Caddy/NGINX with ACME), disk and backup encryption from the platform, a secret store for the database password and API keys with values rendered at deploy, and field-level encryption only for the handful of columns whose exposure would be an incident (casts in Laravel, AES-GCM with a KMS-wrapped key in Go). Concrete example: an online clinic stores patient national ids with the encrypted cast plus a blind index, diagnoses with the encrypted cast, and runs crypto:reencrypt once a year after rotating APP_KEY. The whole cryptographic inventory fits in one table in the README.

Modular monolith: boundaries without the network ​

Modules share a process but not keys: the billing module gets its own KEK and the patient module its own, derived per purpose with HKDF or held as separate KMS keys, so a bug in one module's export cannot decrypt another module's data. Blind-index keys are separate from encryption keys. Secrets are namespaced by module in the store (secret/billing/*, secret/patients/*), even though one deployment reads them, so splitting a module out later does not mean renaming every secret. Example: the billing module's EnvelopeEncrypter uses alias/billing-pii; the patients module uses alias/patients-phi; the key policies already name the future services' roles.

Microservices: every arrow carries an identity ​

Each service gets a workload identity (SPIFFE ID or cloud IAM role), mTLS on every call, its own secrets and its own KEKs. Encrypted fields cross service boundaries as envelopes only when the receiver is meant to decrypt them; otherwise services pass references (a token or an id), not data. Example flow for a checkout:

text
     Step  Caller -> callee                     Transport                       Crypto decision
1    1     browser -> API gateway               TLS 1.3, public cert (ACME)     gateway terminates public TLS
2    2     gateway -> checkout                  mTLS, SVID spiffe://.../gateway  checkout authorises gateway's ID
3    3     checkout -> payments                 mTLS                             card data is a token, never the PAN
4    4     payments -> card vault               mTLS + KMS context              only the vault decrypts the PAN
5    5     payments -> Kafka (payment.captured) TLS + SASL; payload has no PAN   consumers never need the KEK
6    6     each service -> PostgreSQL           TLS verify-full, Vault dynamic user  per-pod credentials, 1 h lease

The service mesh chapter covers sidecars; mTLS covers the authorisation policy.

Distributed data: replicas, caches, regions ​

Replicas, caches and brokers multiply copies of data, and every copy inherits only the protection of its layer. Field-level ciphertext stays ciphertext in read replicas, Redis caches, Kafka topics, Elasticsearch indexes and backups, which is exactly why it is worth its cost; disk encryption protects none of them from a reader with access. Keys must be available where data is read: multi-region KMS keys (AWS KMS multi-region keys, Cloud KMS multi-region locations) or a wrapped DEK per region in the envelope, so a regional KMS outage does not stop reads elsewhere. Caches of plaintext (a Redis cache of decrypted profiles) must be treated as a decrypted copy: encrypt the cache entry, shorten its TTL, or do not cache. Crypto-shredding is the only practical erasure that reaches every replica and backup at once. CDN edges terminate TLS and see plaintext; keep personal data off cacheable responses (CDN).

Scaling path: 1x, 10x, 100x ​

  • 1x: managed certificates, platform disk encryption, one secret store, framework encryption for a few columns, manual yearly rotation with a checklist.
  • 10x: envelope encryption with per-tenant KEKs, a data-key cache to keep KMS calls flat, automated rotation and rewrap jobs with progress metrics, cert-manager or a private CA for internal TLS, secret scanning in CI, dynamic database credentials.
  • 100x: workload identity everywhere (SPIFFE/SPIRE or cloud identities) with hour-long certificates, multi-region KMS keys, an HSM-rooted private PKI with an offline root, policy-as-code for key usage, signed artefacts with admission control, a cryptographic inventory generated from code and infrastructure, and post-quantum readiness tracking (hybrid key exchange is already the Go default).

Lab: keys, nonces and certificates with numbers ​

Experiment 1: nonce budget (run) ​

bash
cd docs/snippets/system-design/cryptography-tls-pki-secrets/go
go run ./cmd/noncemath
# msgs     count            p(96-bit)      p(192-bit)
# 2^20     1048576          6.94e-18       8.76e-47
# 2^28     268435456        4.55e-13       5.74e-42
# 2^32     4294967296       1.16e-10       1.47e-39
# 2^36     68719476736      2.98e-08       3.76e-37
# 2^40     1099511627776    7.63e-06       9.63e-35
# 2^48     281474976710656  0.393          6.31e-30
#
# one key at       100 encryptions/s reaches 2^32 in   11930.5 hours (497.1 days)
# one key at     10000 encryptions/s reaches 2^32 in     119.3 hours (5.0 days)
# one key at   1000000 encryptions/s reaches 2^32 in       1.2 hours (0.0 days)

Experiment 2: the "before" program reuses a nonce (run) ​

bash
go run ./before
# nonce a: 000000000000000000000001
# nonce b: 000000000000000000000001
# same nonce, same key: true

Experiment 3: the test suite, with NIST and RFC vectors (run) ​

bash
gofmt -l . && go vet ./... && go test -race ./...
# ok   academy/cryptography-tls-pki-secrets/envelope
# ok   academy/cryptography-tls-pki-secrets/secrets
# ok   academy/cryptography-tls-pki-secrets/tlsconfig

Experiment 4: inspect a real chain and TLS policy (expected, not run) ​

bash
openssl s_client -connect example.com:443 -servername example.com -showcerts </dev/null 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName
# subject=CN=example.com
# issuer=C=US, O=..., CN=... (an intermediate, not a root)
# notBefore=...  notAfter=...   (difference <= 200 days for certificates issued after 2026-03-15)
# X509v3 Subject Alternative Name: DNS:example.com, DNS:www.example.com
openssl s_client -connect example.com:443 -tls1_1 </dev/null
# ... alert protocol version ... (a modern server refuses TLS 1.1)

Experiment 5: Vault Transit rotate and rewrap (expected, not run) ​

bash
vault secrets enable transit
vault write -f transit/keys/orders
vault write transit/encrypt/orders plaintext=$(echo -n "card-token-123" | base64)
# ciphertext    vault:v1:...
vault write -f transit/keys/orders/rotate
vault write transit/rewrap/orders ciphertext=vault:v1:...
# ciphertext    vault:v2:...          (the plaintext never left Vault)
vault write transit/keys/orders/config min_decryption_version=2
vault write transit/decrypt/orders ciphertext=vault:v1:...
# Error ... (v1 is now below min_decryption_version)

Experiment 6: find a planted secret (expected, not run) ​

bash
git init /tmp/leak && cd /tmp/leak
echo 'AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' > .env && git add . && git commit -qm init
gitleaks git -v
# Finding: AWS_SECRET_ACCESS_KEY=wJalr...   RuleID: aws-secret-access-key (or generic-api-key)   leaks found: 1
trufflehog git file:///tmp/leak --results=verified
# (no verified results: the documentation example key is not live)

Experiment 7: Laravel APP_KEY rotation (expected, not run) ​

bash
php artisan tinker --execute='App\Models\Patient::create(["name"=>"A","national_id"=>"078-05-1120"]);'
OLD=$(grep ^APP_KEY= .env | cut -d= -f2-)
php artisan key:generate --force && echo "APP_PREVIOUS_KEYS=$OLD" >> .env && php artisan config:cache
php artisan tinker --execute='echo App\Models\Patient::first()->national_id;'
# 078-05-1120                      (decrypted with the previous key)
php artisan crypto:reencrypt patients national_id diagnosis contacts
# Rewrote 1 rows in patients. Remove the old key from APP_PREVIOUS_KEYS only after every table reports 0.
php artisan crypto:reencrypt patients national_id diagnosis contacts
# Rewrote 0 rows in patients. ...

Common misconceptions ​

BeliefReality
"Encrypted at rest" means protected from attackersDisk and TDE protect media and files; anyone who can query the database sees plaintext
RSA is for encrypting dataPublic-key crypto agrees on or wraps symmetric keys; AEADs encrypt data
AES-256-CBC is the strongest choiceWithout a MAC it is malleable and vulnerable to padding oracles; use an AEAD
Random nonces never collideThe birthday bound: NIST caps random-IV GCM at 2^32 messages per key
Key rotation re-encrypts the databaseWith envelope encryption it adds a KEK version; rewrap touches only wrapped DEKs
Rotating a key protects data that already leakedCopied ciphertext stays decryptable with the old key until it is destroyed
Revocation will save us if a key leaksBrowsers barely check; Let's Encrypt ended OCSP; short lifetimes are the real control
The Common Name must match the hostClients check the SAN; Go ignores the Common Name
Pinning the leaf certificate is best practiceWith 47-day certificates it guarantees outages; OWASP recommends against pinning in nearly all cases
Environment variables are a secure secret storeThey leak to children, dumps and debug pages; files or an agent are safer
Deleting the commit removes a leaked keyHistory, clones and scrapers keep it; revoke and rotate
A signature proves the artefact is safeIt proves who signed; provenance and admission policy make it a control
We use AWS, so we are FIPS compliantProvider attestations cover the provider; your modules and modes are yours to prove
Laravel's APP_KEY rotation is automatic once APP_PREVIOUS_KEYS is setOld values stay under the old key until rewritten; remove the old key only after re-encryption

Cheat sheet ​

TopicRemember
Data encryptionAES-256-GCM or ChaCha20-Poly1305; XChaCha20 for random nonces at volume
Key agreement / signaturesX25519; Ed25519, ECDSA P-256 under FIPS, RSA-PSS if RSA
Derivation / integrityHKDF-SHA-256 per purpose; HMAC-SHA-256 with constant-time compare
AvoidECB, CBC without MAC, PKCS#1 v1.5 encryption, MD5/SHA-1, custom crypto
Nonce limit2^32 random 96-bit IVs per key (SP 800-38D); DEK per record removes the problem
EnvelopeDEK per value, KEK in KMS, store wrapped DEK + KEK id + version + nonce + ct
RotationNew KEK version; rewrap; raise min decryption version; then destroy
ErasureCrypto-shredding with keys at the granularity of deletion
At restDisk < TDE < field-level; pick by threat; blind index for exact match only
In transitTLS 1.2+ AEAD only, TLS 1.3 preferred; verify certificates on every internal hop
Certificates200 days (2026), 100 (2027), 47 (2029); automate, monitor CT, CAA
RevocationCRL; OCSP being retired; short-lived certificates as the real answer
Private PKIOffline root, online intermediate; step-ca, Vault PKI, AWS Private CA; SPIFFE IDs
SecretsOne store, workload identity, files or agent, dynamic where possible, scan every commit
LaravelAPP_PREVIOUS_KEYS + re-encrypt; encrypted casts need TEXT; env() only in config

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 — Why does TLS 1.3 use both asymmetric and symmetric cryptography, and which does what? Must-know ​

Answer

Answer: Ephemeral ECDHE (for example X25519) agrees on a shared secret and the certificate key signs the handshake (asymmetric); HKDF derives traffic keys and an AEAD such as AES-GCM encrypts the data (symmetric), because public-key operations are slow and size-limited.

2 — A service encrypts 10,000 events per second under one AES-GCM key with random nonces. What limit applies and when is it reached? Good to know ​

Answer

Answer: NIST SP 800-38D limits random-IV GCM to 2^32 encryptions per key; at 10,000 per second that is about 119 hours, roughly five days. Use a DEK per record, XChaCha20-Poly1305, or rotate before the limit.

3 — What is stored next to an envelope-encrypted value, and why each field? Important ​

Answer

Answer: A format version (agility), the KEK id (which key to ask), the KEK version (rotation progress), the wrapped DEK (to recover the data key), the nonce and the ciphertext with its tag. The record identity is bound as AAD but not necessarily stored.

4 — After rotating a KEK in AWS KMS, do you need to rewrap every DEK to keep reading old data? Important ​

Answer

Answer: No. AWS KMS keeps old key material and chooses it on Decrypt. Rewrap (ReEncrypt) is needed only to move to a different key, and in systems like Vault before raising min_decryption_version.

5 — Which attacks does TDE stop and which does it not? Must-know ​

Answer

Answer: It stops reading copied data files and backups off the host. It does not stop SQL injection, a stolen database login, a DBA or a replica reader, because the engine decrypts for any authenticated session.

6 — Why is a blind index on a "country" column a bad idea? Important ​

Answer

Answer: A blind index is deterministic and leaks equality and frequency; with low cardinality the attacker can infer values from frequencies (the most common value is probably the home country). Use it only on high-cardinality fields.

7 — What changes on 15 March 2026, 2027 and 2029 for public TLS certificates? Good to know ​

Answer

Answer: Maximum validity falls to 200 days, then 100 days, then 47 days (CA/Browser Forum Baseline Requirements after Ballot SC-081), and domain-validation reuse falls to 10 days by 2029.

8 — Why is pinning the leaf certificate in a mobile app risky, and what is the safer alternative? Important ​

Answer

Answer: The leaf changes at every renewal, so the app breaks; OWASP says pinning creates more risk than reward in nearly all cases. If you must pin, pin your own CA or SPKI with an offline backup key, and only when you control both ends.

9 — Why should an application not fall back to an environment variable when Vault returns 403? Must-know ​

Answer

Answer: A hard error means misconfiguration or revocation; silently using a stale value can keep a revoked credential alive or hide an outage. Fall through only on "not found", as the Go Chain does.

10 — After setting a new APP_KEY and putting the old one in APP_PREVIOUS_KEYS, when can the old key be removed? Important ​

Answer

Answer: After every encrypted value has been rewritten under the new key (the crypto:reencrypt command reports zero rows for every table) and old session cookies have expired.

11 — What does a cosign keyless signature prove, and what must the verifier check? Good to know ​

Answer

Answer: That an identity authenticated by an OIDC issuer signed this digest at a time recorded in Rekor. The verifier must check the expected certificate identity and OIDC issuer, not merely that some signature exists.

12 — Why are dynamic database credentials better than a rotated shared password? Important ​

Answer

Answer: Each instance gets its own short-lived user with a lease, so a leak is traceable and expires on its own, and revoking one lease drops one user without touching the others.

Glossary ​

TermMeaning
Symmetric encryptionOne shared key encrypts and decrypts (AES, ChaCha20)
Asymmetric encryptionA public/private key pair; used for key agreement, signatures and wrapping small values
AEADAuthenticated Encryption with Associated Data: confidentiality plus integrity of ciphertext and AAD
AADAssociated data: authenticated, not encrypted (row id, tenant, table)
AES-256-GCMAES with a 256-bit key in Galois/Counter Mode; the default AEAD
ChaCha20-Poly1305Stream-cipher AEAD from RFC 8439; fast without AES hardware
XChaCha20ChaCha20 variant with a 192-bit nonce, safe for random nonces at volume
AES-GCM-SIVNonce-misuse-resistant AEAD (RFC 8452)
NonceNumber used once per encryption under a key
IVInitialization vector; GCM's name for its nonce
Nonce reuseUsing the same nonce twice under one key; catastrophic for GCM and ChaCha20-Poly1305
X25519ECDH key agreement over Curve25519 (RFC 7748)
ECDHElliptic-curve Diffie-Hellman key agreement
X25519MLKEM768Hybrid classical + post-quantum key exchange, Go's TLS default since 1.24
Ed25519EdDSA signatures over Curve25519 (RFC 8032)
ECDSAElliptic-curve signatures, usually over P-256; FIPS approved
RSA-PSSProbabilistic RSA signature padding
RSA-OAEPRSA encryption padding that resists chosen-ciphertext attacks
RSA PKCS#1 v1.5Legacy RSA padding; its encryption mode is vulnerable to Bleichenbacher attacks
HKDFHMAC-based key derivation (RFC 5869): extract, then expand per purpose
HMACKeyed hash MAC; HMAC-SHA-256 for integrity with a shared key
SHA-256SHA-2 hash with a 256-bit output
MD5, SHA-1Broken hash functions; collisions are practical
Argon2idMemory-hard password hash (RFC 9106)
ECBBlock mode that encrypts equal blocks identically; never use
CBCBlock mode needing a MAC; without one it is malleable
Padding oracleAn error difference that lets an attacker decrypt CBC ciphertext
Custom cryptoHome-made algorithms or protocols; do not
Envelope encryptionData encrypted with a DEK; the DEK encrypted with a KEK
DEKData encryption key; fresh per value or object
KEKKey encryption key; wraps DEKs, stays in the KMS
KMSKey management service (AWS KMS, Cloud KMS, Azure Key Vault, Vault Transit)
Root keyThe top of the hierarchy, kept in an HSM
Key hierarchyTree of keys, each level protecting the one below
Key rotationCreating a new key version for new encryptions
Re-wrapRe-encrypting a wrapped DEK under a new KEK version without exposing it
min_decryption_versionVault Transit setting that refuses older key versions
Encryption contextAWS KMS name for AAD bound to a data key, logged in CloudTrail
Data-key cachingReusing a plaintext DEK briefly to save KMS calls
Crypto-shreddingDeleting data by destroying the key that encrypts it
HSMHardware security module: keys generated and used inside tamper-resistant hardware
FIPS 140-3US/Canadian standard for validating cryptographic modules
CMVPNIST program that validates modules under FIPS 140-3
GOFIPS140Go build setting selecting the FIPS 140-3 Go Cryptographic Module
CryptoperiodTime a key is authorized for use (NIST SP 800-57)
Encryption at restProtection of stored data: disk, TDE, field-level
TDETransparent data encryption inside the database engine
Field-level encryptionApplication encrypts values before storing them
Searchable encryptionTechniques that keep some query ability over ciphertext
Deterministic encryptionSame plaintext gives same ciphertext; leaks equality
Convergent encryptionVault Transit's deterministic mode
Blind indexKeyed HMAC of a normalized value for exact-match lookup
TokenisationReplacing sensitive values with tokens held in a vault
Encryption in transitProtecting data on the network, normally with TLS
TLS 1.3RFC 8446; AEAD-only, forward secrecy always
Cipher suiteThe algorithm set a TLS connection uses
Forward secrecyPast sessions stay safe if a long-term key leaks later
0-RTTTLS 1.3 early data; replayable, idempotent requests only
TLS terminationWhere a TLS connection ends and plaintext exists
TLS passthroughLoad balancer forwards encrypted bytes; backend terminates
HSTSHeader telling browsers to use HTTPS only
mTLSMutual TLS: both sides present certificates
Certificate pinningClient accepts only a specific certificate or key
PKIPublic key infrastructure: CAs, certificates, revocation, trust stores
Certificate authorityEntity that signs certificates
Root CASelf-signed CA in trust stores, kept offline
Intermediate CACA signed by the root that issues leaves
ChainLeaf, intermediates and root forming a validation path
CSRCertificate signing request (PKCS#10)
SANsubjectAltName extension listing the names a certificate is valid for
EKUExtended key usage: serverAuth, clientAuth, codeSigning
Validity periodnotBefore to notAfter
CRLCertificate revocation list
OCSPOnline Certificate Status Protocol (RFC 6960)
OCSP staplingServer attaches a fresh OCSP response in the handshake
Short-lived certificateCertificate short enough that revocation is unnecessary
Certificate TransparencyPublic append-only logs of issued certificates (RFC 6962)
SCTSigned certificate timestamp, proof of CT logging
CAADNS record restricting which CAs may issue for a domain
ACMEAutomated Certificate Management Environment (RFC 8555)
Let's EncryptFree public ACME CA
http-01, dns-01, tls-alpn-01ACME challenge types
Private PKIA CA hierarchy you run for internal names and workloads
step-casmallstep's online private CA with ACME and OIDC provisioners
Vault PKIHashiCorp Vault secrets engine that issues certificates
cert-managerKubernetes controller that issues and renews certificates
SPIFFEStandard for workload identity (spiffe:// IDs)
SPIREReference implementation of SPIFFE
SVIDSPIFFE Verifiable Identity Document (X.509-SVID, JWT-SVID)
Trust bundleSet of CA certificates a workload trusts for a trust domain
Secrets managementCentralised storage, access, audit and rotation of secrets
VaultHashiCorp's secrets manager (KV, dynamic secrets, PKI, transit)
Secrets ManagerAWS managed secrets store with rotation
Parameter StoreAWS Systems Manager parameters, SecureString via KMS
Secret ManagerGoogle Cloud's managed secrets store
Azure Key VaultAzure store for secrets, keys and certificates
sealed-secretsBitnami controller decrypting secrets sealed to a cluster key
External Secrets OperatorKubernetes operator syncing external stores into Secrets
SOPSTool encrypting values in YAML/JSON/ENV files with age, PGP or KMS
ageSmall file encryption tool and format with X25519 recipients
Dynamic secretsCredentials generated on request, with a lease
LeaseVault metadata with TTL and renewability attached to a dynamic secret
Secret rotationReplacing a secret on a schedule or after an incident
Secret injectionHow a secret reaches a process: env, file, sidecar, API
SidecarHelper container next to the app (Vault Agent, Envoy)
Workload identityCredentials derived from what the workload is (IAM role, SPIFFE ID)
Secret sprawlUncontrolled spread of secrets across systems
gitleaksPattern-based secret scanner for git and directories
trufflehogSecret scanner with live verification of found credentials
SigstoreSigning infrastructure: Fulcio CA, Rekor log
cosignSigstore's tool to sign and verify containers and blobs
RekorSigstore transparency log for signatures
SLSASupply-chain Levels for Software Artifacts, build levels L0 to L3
CSPRNGCryptographically secure random number generator
crypto/randGo's CSPRNG package (Read, Text)
random_bytesPHP's CSPRNG function
APP_KEYLaravel's application encryption key
APP_PREVIOUS_KEYSLaravel's comma-separated list of old keys accepted for decryption
Encrypted castEloquent cast that encrypts an attribute with Crypt
CryptLaravel facade for the encrypter
config:cacheLaravel command that caches configuration; .env is not loaded afterwards

References ​

Built by Morteza Negahi