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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why systems need more than "use HTTPS" | Why it exists |
| From Diffie-Hellman to 47-day certificates | Where it comes from |
| Symmetric vs asymmetric, and why every system uses both | Symmetric vs asymmetric |
| Which algorithm for which job | Choosing primitives |
| ECB, CBC without a MAC, PKCS#1 v1.5, MD5, SHA-1, custom crypto | What to avoid |
| 2^32 messages per key, XChaCha20, AES-GCM-SIV | Nonces and IVs at scale |
| DEK, KEK, KMS, GenerateDataKey | Envelope encryption |
| Key versions, rotation, rewrap, min decryption version | Key hierarchy and rotation |
| Deleting data by deleting a key | Crypto-shredding |
| Generation, storage, HSM, destruction, FIPS 140-3 | Key management lifecycle |
| Disk, TDE, field-level, searchable encryption | Encryption at rest |
| TLS everywhere, TLS 1.3, cipher suite policy, termination | Encryption in transit |
| Internal mTLS and certificate pinning | mTLS and pinning |
| CA, intermediate, chain, CSR, SAN | PKI |
| 398, 200, 100, 47 days; CRL, OCSP, stapling; CT | Validity and revocation |
| ACME, Let's Encrypt, step-ca, Vault PKI, cert-manager, SPIFFE | ACME and private PKI |
| Vault, Secrets Manager, Parameter Store, Secret Manager | Secrets management |
| Dynamic secrets, leases, rotation | Dynamic secrets |
| Env vs file vs sidecar vs API, sealed-secrets, ESO, SOPS | Secret injection |
| gitleaks, trufflehog | Secret sprawl |
| Sigstore, cosign, SLSA | Signing artefacts |
crypto/rand, random_bytes | Randomness |
| "We are FIPS compliant" and other claims | Compliance claims |
| Knobs and error messages | Mechanics |
| Code | Go, Laravel |
| Leaked key, expired certificate, APP_KEY rotation, erasure | Solving the classic problems |
| What to pick for which data | Choosing |
| Monolith to distributed system | In architecture |
| Runnable numbers and expected outputs | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Primitive by job.
| Job | Use | Avoid | Go | PHP / Laravel |
|---|---|---|---|---|
| Encrypt data (AEAD) | AES-256-GCM; ChaCha20-Poly1305 where there is no AES hardware; XChaCha20-Poly1305 for random nonces at volume | ECB, CBC without a MAC, AES-CTR alone | crypto/cipher.NewGCM, x/crypto/chacha20poly1305 | openssl_encrypt('aes-256-gcm'), sodium_crypto_aead_xchacha20poly1305_ietf_encrypt, Crypt |
| Agree on a key | X25519 (ECDH); X25519MLKEM768 hybrid in TLS | Static RSA key transport | crypto/ecdh | sodium_crypto_kx_* |
| Sign | Ed25519; ECDSA P-256 where FIPS or WebPKI need it; RSA-PSS for RSA | RSA PKCS#1 v1.5 for new designs, DSA | crypto/ed25519, crypto/ecdsa | sodium_crypto_sign_*, openssl_sign |
| Encrypt to a public key | RSA-OAEP, or ECDH + AEAD (HPKE, age) | RSA PKCS#1 v1.5 encryption | rsa.EncryptOAEP | openssl_public_encrypt(..., OPENSSL_PKCS1_OAEP_PADDING) |
| Derive keys | HKDF-SHA-256 | Raw SHA-256 of a key, reusing one key for two purposes | crypto/hkdf | hash_hkdf('sha256', ...) |
| Integrity with a shared key | HMAC-SHA-256 | sha256(key + message), MD5, SHA-1 | crypto/hmac | hash_hmac('sha256', ...), signed URLs |
| Store passwords | Argon2id (bcrypt acceptable) | Any fast hash, any encryption | x/crypto/argon2 | Hash::make with the argon2id driver |
| Random keys, nonces, tokens | OS CSPRNG | math/rand, mt_rand, uniqid, time-based seeds | crypto/rand.Read, rand.Text | random_bytes, Str::random |
Where plaintext exists, by layer.
| Layer | Who still sees plaintext | Stops | Does not stop |
|---|---|---|---|
| TLS in transit | Each TLS endpoint: load balancer, proxy, service | Network sniffing, Wi-Fi, ISP, a compromised switch | Anything after the terminating proxy |
| Disk / volume encryption | Every process on the running host | A stolen or decommissioned disk, a snapshot leaked to another account | Root, the database, the application |
| Database TDE | Anyone who can log in to the database | Copied data files and backups | SQL injection, a DBA, a replica reader |
| Field-level / application encryption | Only code holding the key (via KMS) | Database dumps, injection, analysts, logs of SQL | A compromised application process |
| End-to-end | Only the endpoints (users' devices) | The server operator | A compromised endpoint |
Lifetimes to remember.
| Thing | Number | Source |
|---|---|---|
| Random 96-bit GCM nonces under one key | at most 2^32 encryptions | NIST SP 800-38D, section 8.3 |
| Public TLS leaf certificate, from 2026-03-15 | 200 days max | CA/Browser Forum Baseline Requirements |
| ... from 2027-03-15 / 2029-03-15 | 100 days / 47 days | Ballot SC-081 schedule in the BRs |
| Let's Encrypt default / short-lived profile | 90 days / six days | Let's Encrypt announcement (January 2025) |
| AWS KMS automatic rotation default | 365 days | AWS KMS developer guide |
| Symmetric data-encryption key originator usage | up to two years | NIST 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.
| Rule | Why |
|---|---|
| Never write crypto, compose it from a maintained library | OWASP: "Custom Algorithms: Don't do this." |
| One key, one purpose; derive subkeys with HKDF | A key reused across purposes breaks the proofs of both |
| Data keys are many and short-lived; master keys are few and never leave an HSM | That is envelope encryption |
| Every ciphertext carries a key id and version | Rotation without archaeology |
| Every certificate renewal is automated and monitored | 47-day certificates make manual renewal an outage plan |
| Secrets come from a store at run time, not from git, images or build args | Git history is forever |
| Prefer credentials that expire on their own (leases, short-lived certificates) | Revocation is the least reliable part of every system |
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 design | With a design |
|---|---|
| One AES key in an environment variable encrypts everything | Per-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 backup | Destroying their KEK makes every copy unreadable |
| Certificates renewed by a calendar reminder | ACME or a private CA renews them automatically, alerts on failure |
| Database passwords shared by every service for years | Dynamic credentials per instance, expiring in an hour |
Secrets in .env files, CI variables, Slack and git history | One 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
- "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.
- "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.
- "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).
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 optionThe 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.
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).
| Property | Symmetric (AES-GCM, ChaCha20-Poly1305, HMAC) | Asymmetric (X25519, Ed25519, ECDSA, RSA) |
|---|---|---|
| Keys | One shared secret | Public + private pair |
| Speed | Very fast, hardware accelerated | Slow; RSA-2048 signing is thousands per second per core |
| Data size | Any | Small (an RSA-2048 OAEP block holds 190 bytes with SHA-256) |
| Key distribution problem | Hard: both sides need the secret | Easy: publish the public key, certify it |
| Typical use | Bulk data, storage, MACs | Key agreement, signatures, identity, wrapping keys |
| Non-repudiation | No (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).
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 / library | Default data cipher | Signatures | Notes |
|---|---|---|---|
| Go stdlib | AES-GCM via cipher.NewGCM; ChaCha20 in x/crypto | Ed25519, ECDSA, RSA-PSS | crypto/hkdf since Go 1.24 |
| libsodium / PHP sodium | XChaCha20-Poly1305 (secretbox is XSalsa20) | Ed25519 | Misuse-resistant APIs, no algorithm choices to get wrong |
Laravel Crypt | AES-256-CBC + HMAC-SHA-256 (encrypt-then-MAC) | n/a | aes-256-gcm supported via app.cipher |
| AWS KMS | AES-256-GCM (symmetric keys) | RSA-PSS, ECDSA keys | KEKs live in FIPS 140-3 Level 3 HSMs |
| HashiCorp Vault Transit | aes256-gcm96 default | ed25519, ecdsa-p256, rsa-* | Convergent mode available for deterministic encryption |
| Google Tink | AES-GCM, AES-GCM-SIV, XChaCha20 | Ed25519, ECDSA | Key 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:
| Avoid | Why | Instead |
|---|---|---|
| ECB mode | Encrypts equal blocks to equal ciphertext: patterns survive (the famous penguin picture) | Any AEAD |
| CBC (or CTR) without a MAC | Malleable; CBC with error-revealing decryption is a padding oracle (Vaudenay 2002) that decrypts byte by byte | AEAD, or encrypt-then-MAC as Laravel does |
| RSA PKCS#1 v1.5 encryption | Bleichenbacher's adaptive chosen-ciphertext attack (1998) and its ROBOT revival | RSA-OAEP, or ECDH + AEAD |
| Raw RSA, RSA without padding | Deterministic and malleable | OAEP for encryption, PSS for signatures |
| MD5, SHA-1 for any security purpose | Practical collisions | SHA-256, SHA-3, BLAKE2/3 |
hash(key + message) as a MAC | Length-extension attacks on SHA-256 | HMAC-SHA-256 |
| Fast hashes for passwords | GPUs test billions per second | Argon2id, bcrypt, scrypt |
| Custom ciphers, home-made protocols | Unreviewed; OWASP: "Custom Algorithms: Don't do this." | TLS, HPKE, age, libsodium, Tink |
| Static IVs, counters reset on restart | Nonce reuse destroys GCM | Random nonces within limits, XChaCha20, SIV |
== to compare MACs or tokens | Timing side channel | hmac.Equal, hash_equals |
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 oracleReal 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".
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.
| Approach | Nonce rule | Limit per key | Products |
|---|---|---|---|
| AES-GCM, random 96-bit IV | Random from a CSPRNG | 2^32 encryptions (SP 800-38D) | Go NewGCM, OpenSSL, AWS KMS internally |
| AES-GCM, deterministic counter | Unique fixed field per device + counter | 2^32 per fixed field, counter must survive restarts | TLS record layer (sequence number XOR IV) |
| ChaCha20-Poly1305 | 96-bit, never repeat | Same birthday reasoning as GCM | RFC 8439, WireGuard (counter), TLS 1.3 |
| XChaCha20-Poly1305 | 192-bit random | Random nonces practically unlimited | libsodium, x/crypto/chacha20poly1305.NewX, age payload uses ChaCha20-Poly1305 with derived keys |
| AES-GCM-SIV | Repeats leak only equality | Misuse-resistant, not misuse-free | Tink, BoringSSL, RFC 8452 |
| Envelope, DEK per record | Any random nonce, one message per key | Bounded by KMS calls instead | AWS 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".
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.
| Product | Generate DEK | Unwrap | Rewrap | Context / AAD | Notes |
|---|---|---|---|---|---|
| AWS KMS | GenerateDataKey, GenerateDataKeyWithoutPlaintext | Decrypt | ReEncrypt (server side) | EncryptionContext, logged in CloudTrail | AWS Encryption SDK adds data-key caching |
| Google Cloud KMS | Generate locally, Encrypt to wrap | Decrypt | Decrypt + Encrypt with new primary | additionalAuthenticatedData | 64 KiB max input; key ring / key / version hierarchy |
| Azure Key Vault | Generate locally, wrapKey | unwrapKey | unwrap + wrap | n/a for RSA wrap | RSA-OAEP or AES key wrap; Managed HSM for FIPS Level 3 |
| HashiCorp Vault Transit | transit/datakey/plaintext/:name | transit/decrypt/:name | transit/rewrap/:name | context with derived keys | Ciphertext prefixed vault:v1: with the key version |
| Google Tink / AWS Encryption SDK | Library-managed | Library-managed | Library-managed | Built in | Multi-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.
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).
| Product | Rotation | Old versions | Rewrap | Retire old versions |
|---|---|---|---|---|
| AWS KMS | Automatic (default 365 days, custom period) or on demand | Kept forever, transparent on Decrypt | ReEncrypt to another key | Not per version; schedule key deletion (7 to 30 days) |
| Google Cloud KMS | Automatic rotation schedule | Enabled versions decrypt | Decrypt + Encrypt | Disable then destroy a version |
| Azure Key Vault | Rotation policy | Kept as versions | unwrap + wrap | Disable a version |
| Vault Transit | transit/keys/:name/rotate, auto_rotate_period | Working set | transit/rewrap/:name | min_decryption_version, then trim |
Laravel APP_KEY | Manual: new APP_KEY, old into APP_PREVIOUS_KEYS | Tried in order on decrypt | Re-encrypt every value | Remove 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).
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 noiseReal 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.
| Granularity | Keys to manage | Erasure unit | Fits |
|---|---|---|---|
| One KEK for everything | 1 | None (all or nothing) | Not crypto-shredding |
| Per tenant | Tenants (hundreds to thousands) | Tenant offboarding | B2B SaaS |
| Per user / data subject | Users (millions): use derived or wrapped per-user keys under a tenant KEK | One person | GDPR erasure in event stores and logs |
| Per dataset or partition | Datasets | One export or one month of data | Analytics, 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.
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 approvalReal 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.
| Option | Who holds the root | FIPS 140-3 | Trade-off |
|---|---|---|---|
| AWS KMS / Cloud KMS / Key Vault (software or HSM tier) | Cloud provider HSMs | Level 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 HSM | Level 3 | You run clusters, backups, quorum |
| External key store (AWS XKS, Google EKM) | Your on-premises HSM | Your module's level | Every decrypt depends on your HSM's availability |
| Vault with HSM auto-unseal (Enterprise) or KMS seal | Vault, rooted in an HSM or cloud KMS | Depends on the seal | Portable across clouds |
Go Cryptographic Module (GOFIPS140) | Your process | CMVP validation of the module | Approved 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.
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.
| Technique | Query ability | Leaks | Products |
|---|---|---|---|
| Randomized AEAD (default) | None | Length | Laravel encrypted cast, Go AES-GCM, Tink |
| Deterministic (AES-SIV, Vault convergent) | Equality, joins, unique | Equality, frequency | Vault Transit convergent_encryption, Tink Deterministic AEAD, MongoDB CSFLE deterministic |
| Blind index (HMAC) | Exact match on a separate column | Equality of the indexed value | CipherSweet (PHP), hand-written HMAC column |
| Queryable / structured encryption | Equality, range (product-specific) | Documented, product-specific | MongoDB Queryable Encryption |
| Tokenisation | Lookup through the vault | Nothing in the app DB | Payment 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.
-- 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.
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 databaseReal 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.
| Product | Protocol knob | Cipher knob | Defaults worth knowing |
|---|---|---|---|
Go crypto/tls | MinVersion, MaxVersion | CipherSuites (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 |
| NGINX | ssl_protocols TLSv1.2 TLSv1.3; | ssl_ciphers, ssl_conf_command Ciphersuites | ssl_stapling on; for OCSP stapling |
| HAProxy | ssl-min-ver TLSv1.2 | ciphers, ciphersuites | ssl-default-bind-options in global |
| AWS ALB / NLB | Security policy name | Same (policy) | Pick one of the ELBSecurityPolicy-TLS13-* policies |
| Envoy | tls_minimum_protocol_version | cipher_suites | Set 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 only | The 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.
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 updateReal 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.
| Option | Protects against | Breaks when | Recommendation |
|---|---|---|---|
| Standard WebPKI validation + CT | Most misissuance (CT makes it visible) | Never by itself | Default |
| mTLS with a private CA | Unauthenticated callers inside the network | CA rotation is not automated | Default for service to service |
| Pin leaf certificate | Misissued certificates | Every renewal | Avoid |
| Pin your own intermediate / SPKI with a backup | Misissuance by public CAs | Your CA rotation is not planned | Only 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.
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, revocationReal 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.
| Concept | Public WebPKI | Private PKI |
|---|---|---|
| Root | In browser/OS trust stores, audited (WebTrust, ETSI) | Distributed by you (MDM, config management, trust bundles) |
| Issuance validation | Domain control (ACME challenges), OV/EV checks | Whatever your policy says: workload attestation, IAM, SSO |
| Lifetimes | 200 days now, 47 days by 2029 | Hours to days for workloads |
| Revocation | CRLs (OCSP being retired by Let's Encrypt) | Often none: short lifetimes instead |
| Transparency | CT logs mandatory for browser trust | Optional |
| Names | Public DNS names, public IPs | Internal 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.
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 daysReal 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.
| Mechanism | How the client learns | Privacy | Reliability | Status |
|---|---|---|---|---|
| CRL | Downloads the CA's list | Good | Large lists, stale between updates | Let's Encrypt's only mechanism since 2025 |
| OCSP | Asks the CA per certificate | Poor (CA sees what you visit) | Soft-fail when unreachable | Being retired by Let's Encrypt |
| OCSP stapling | Server staples a signed response | Good | Server bugs can cause downtime | NGINX ssl_stapling on |
| Short-lived certificates | Certificate expires before revocation matters | Good | Requires automation | Let's Encrypt six-day profile, SPIFFE SVIDs |
| CT + monitoring | Not a client check: owner detects misissuance | Public by design | High | Mandatory 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).
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 restartReal 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.
| Product | Protocols | Typical lifetime | Strength | Watch out |
|---|---|---|---|---|
| Let's Encrypt | ACME | 90 days, or six days | Free, public trust, CT | Rate limits; public names only (and IPs with six-day certs) |
| cert-manager | ACME, Vault, Venafi, CA issuers | From the issuer | Kubernetes-native renewal | Secrets in etcd: encrypt etcd |
| smallstep step-ca | ACME, OIDC, JWK, cloud IIDs, SCEP | Hours to days | Self-hosted, ACME for internal names | You run the CA's availability |
| Vault PKI | HTTP API, ACME (Vault 1.14+) | Minutes to days | Tied to Vault auth and policies | Intermediate key lives in Vault's barrier |
| AWS Private CA | API, ACM integration | Your choice | Managed HSM-backed CA | Per-CA monthly price |
| SPIFFE / SPIRE | Workload API, X.509-SVID, JWT-SVID | Minutes to hours | Attested identity, federation | Another 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...).
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 TTLReal 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.
| Product | Best for | Rotation | Pricing model (shape) | Notes |
|---|---|---|---|---|
| HashiCorp Vault | Multi-cloud, dynamic secrets, PKI, transit | Engines rotate or issue on demand | Self-hosted or HCP | Strongest feature set, you operate it |
| AWS Secrets Manager | AWS workloads, RDS credentials | Managed rotation with Lambda | Per secret per month + API calls | Native RDS/Redshift/DocumentDB rotation |
| AWS SSM Parameter Store | Configuration plus some secrets | None built in | Standard parameters free | SecureString uses KMS |
| GCP Secret Manager | GCP workloads | Rotation notifications (Pub/Sub) | Per version + access | IAM per secret, regional replication policies |
| Azure Key Vault | Azure workloads | Rotation policies for keys/certs | Per operation | Secrets, keys, certificates in one place |
| Kubernetes Secret | Delivery into pods | None | Free | Enable etcd encryption with a KMS provider |
| sealed-secrets / SOPS + age | GitOps repositories | Re-encrypt and commit | Free | Git 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.
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 droppedReal 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.
| Approach | Lifetime | Blast radius of a leak | Cost |
|---|---|---|---|
| Static shared password | Years | Every service, untraceable | Cheap until it leaks |
| Static, rotated on schedule (Secrets Manager, Vault static role) | Days to months | Every holder until the next rotation | Rotation logic and client reloads |
| Dynamic per instance (Vault database engine) | Minutes to hours | One instance, traceable by username | Vault availability is on the critical path; many DB roles |
| Workload identity, no secret (IAM roles, GCP workload identity, SPIFFE) | Minutes, automatic | One workload, short window | Best 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.
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 logsReal 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.
| Pattern | Products | Refresh | Code coupling | Use when |
|---|---|---|---|---|
| Env var | Kubernetes env.valueFrom.secretKeyRef, ECS secrets, Docker -e | Restart | None | Short-lived processes, legacy apps |
| File | Kubernetes Secret volume, Secrets Store CSI Driver, Docker secrets | Automatic (eventually) | Read a file | Default for containers |
| Sidecar / agent | Vault Agent, Vault Agent Injector, AWS Secrets Manager agent | Lease-driven | Read a file or call localhost | Dynamic secrets without SDK code |
| API | Vault SDK, AWS SDK, GCP client libraries | Per call | High | When the app must request per-tenant or per-job secrets |
| GitOps sync | ESO, sealed-secrets, SOPS (with Flux or Argo CD) | On sync | None | Declarative 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.
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.
| Tool | Where it runs | Verification | Notes |
|---|---|---|---|
| gitleaks | pre-commit, CI, gitleaks git / gitleaks dir | No (pattern + entropy) | Fast, simple config, baseline files for old findings |
| TruffleHog | CI, scheduled scans, many sources | Yes, --results=verified | Fewer false positives, slower |
| GitHub secret scanning + push protection | On push to GitHub | Partner validation | Blocks known token formats before they land |
| Container scanners (Trivy, Grype) | Image builds | No | Find 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".
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 imagesReal 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.
| Option | Key management | Verification identity | Transparency |
|---|---|---|---|
| cosign keyless (Sigstore) | Ephemeral keys, Fulcio certificates | OIDC identity of the workflow | Rekor |
| cosign with a KMS key | AWS/GCP/Azure KMS or Vault key | Public key | Optional Rekor |
| GPG-signed releases | Long-lived private keys | Key fingerprint | None |
| Notation (Notary v2) | Certificates from your PKI | X.509 chain | Optional |
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".
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 goodReal scenarios: password-reset tokens, API keys, session ids, CSRF tokens, AES keys and nonces, idempotency keys that must not be guessable, invitation codes.
| Language | Use | Never for secrets |
|---|---|---|
| Go | crypto/rand.Read, rand.Text, rand.Int | math/rand, math/rand/v2 (fine for jitter) |
| PHP / Laravel | random_bytes, random_int, Str::random, Str::password | rand, mt_rand, uniqid, lcg_value |
| Node.js | crypto.randomBytes, crypto.randomUUID | Math.random |
| Python | secrets.token_bytes, secrets.token_urlsafe | random |
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).
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 notReal 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).
| Framework | What it asks about cryptography (shape) |
|---|---|
| PCI DSS v4 | Strong cryptography for stored and transmitted card data, documented key management, key custodians |
| FIPS 140-3 / FedRAMP | Validated modules in approved mode |
| HIPAA Security Rule | Encryption as an addressable safeguard, risk-based |
| GDPR Art. 32 | Encryption and pseudonymisation as appropriate measures |
| SOC 2 | Documented 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
| Knob | Product | Value this chapter recommends | Why |
|---|---|---|---|
MinVersion | Go crypto/tls | tls.VersionTLS12 (or 1.3 internally) | Default is 1.2 already; make it explicit |
CipherSuites | Go crypto/tls | ECDHE + AES-GCM / ChaCha20 only | Affects TLS 1.2 only |
ssl_protocols / ssl_ciphers | NGINX | TLSv1.2 TLSv1.3, the Intermediate cipher list | Public compatibility |
ssl_stapling on; ssl_stapling_verify on; | NGINX | On where the CA still runs OCSP | Not useful with Let's Encrypt after 2025 |
| Rotation period | AWS KMS | 365 days (default) or shorter by policy | Old material kept automatically |
min_decryption_version, auto_rotate_period | Vault Transit | Raise only after rewrap reaches zero | Retires old versions |
convergent_encryption, derived | Vault Transit | Only for fields that need equality | Deterministic encryption leaks equality |
default_lease_ttl, max_lease_ttl | Vault | 1 h / 24 h for database roles | Short credentials |
renewBefore, duration | cert-manager Certificate | Renew at 2/3 of lifetime | Room for retries |
cipher, key, previous_keys | Laravel config/app.php | AES-256-CBC (default) or AES-256-GCM | Rotation via APP_PREVIOUS_KEYS |
GOFIPS140, GODEBUG=fips140=on | Go toolchain | Only where FIPS is required | Approved algorithms only in TLS |
--encryption-provider-config | Kubernetes API server | KMS v2 provider | etcd Secrets encrypted with a KMS-wrapped DEK |
The envelope format, byte by byte
| Field | Size | Purpose |
|---|---|---|
| Format version | 1 byte (0x01) | Crypto agility: a new layout or algorithm gets a new version |
| KEK id length + KEK id | 1 + up to 255 bytes | Which KMS key wrapped the DEK (rotation, shredding, routing to a region) |
| KEK version | 4 bytes | Which version; drives rewrap progress |
| Wrapped DEK length + wrapped DEK | 2 + n bytes | The KMS ciphertext blob |
| Nonce | 12 bytes | Random, one per DEK |
| Ciphertext + tag | plaintext + 16 bytes | AES-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
GenerateDataKeyper write and oneDecryptper 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
TEXTvalue of a few hundred bytes.
Error messages you will see
| Message (verbatim) | Where | Meaning | Action |
|---|---|---|---|
cipher: message authentication failed | Go cipher.AEAD.Open | Wrong key, wrong AAD, wrong nonce or tampered data | Check the key version and the AAD binding; do not retry |
crypto/aes: invalid key size 31 | Go aes.NewCipher | Key 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 authority | Go TLS client | Missing intermediate or private CA not in RootCAs | Serve the full chain; add the CA bundle |
x509: certificate is valid for example.com, *.example.com, not orders.internal.test | Go TLS client | Name not in the SAN | Fix the certificate or the ServerName |
remote error: tls: protocol version not supported | Go TLS client | Server refused the offered versions | Upgrade the client; do not lower the server |
tls: client offered only unsupported versions: [302 301] | Go TLS server log | A TLS 1.1/1.0 client was refused | Expected after enforcing TLS 1.2 |
The MAC is invalid. | Laravel DecryptException | Value encrypted with another key, or modified | Add the old key to APP_PREVIOUS_KEYS |
The payload is invalid. | Laravel DecryptException | Not a Laravel encrypted payload (plaintext, truncated column) | Check column length and migrations |
Unsupported cipher or incorrect key length. Supported ciphers are: ... | Laravel Encrypter | APP_KEY length does not match app.cipher | Run php artisan key:generate for the cipher |
InvalidCiphertextException | AWS KMS Decrypt | Wrong encryption context, wrong key, or corrupted blob | Send the same context used on encrypt |
AccessDeniedException | AWS KMS | Key policy or IAM denies the caller | Fix the key policy, not the code |
permission denied (HTTP 403) | Vault | Token lacks the policy for the path | Check the role's policy |
SSL certificate problem: unable to get local issuer certificate | curl / OpenSSL | Missing intermediate or root | Serve 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.
// 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.
// 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.
// 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)
}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.
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.
// 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.
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.
// 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
}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.
// 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
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
// 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
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
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
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
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
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
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
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
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
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
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
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
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:
# 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 optimizeThe feature tests use a fake KMS provider and the framework's Encrypter directly.
<?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
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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Revoke and rotate first | Deactivate at the provider, issue a new key, deploy | Ends the exposure | Requires a rotation path you have practised |
| Investigate | Provider access logs (CloudTrail, Stripe logs) for the exposure window | Know what was done | Time |
| Clean history | git filter-repo, force push, ask forks to delete | Stops future rediscovery | Does not remove existing clones |
| Prevent | gitleaks pre-commit, push protection, TruffleHog in CI | Blocks the next one | False positives to triage |
Rotating Laravel's APP_KEY without logging everyone out
| Step | Action | Effect |
|---|---|---|
| 1 | Move the current key to APP_PREVIOUS_KEYS, set a new APP_KEY (php artisan key:generate --show), deploy, config:cache | New values use the new key; sessions and old values still decrypt |
| 2 | Run php artisan crypto:reencrypt patients national_id diagnosis contacts per table | Values move to the new key |
| 3 | Wait one session lifetime | Old session cookies expire naturally |
| 4 | Remove the old key from APP_PREVIOUS_KEYS | The old key is retired |
A certificate expired in production
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Automate renewal | cert-manager, Caddy, certbot timers, AWS ACM managed renewal | No human in the loop | Must monitor the automation itself |
| Monitor from outside | Blackbox exporter probe_ssl_earliest_cert_expiry, synthetic checks | Catches the forgotten load balancer | One more alert |
| Hot reload | GetCertificate reloader, NGINX reload, Envoy SDS | Renewal without restarts | Code or config per server |
| Inventory | CT logs for public names, CA issuance logs for private ones | Finds certificates nobody owns | Process |
Nonce reuse or too many messages under one key
| Solution | How | Advantage | Cost |
|---|---|---|---|
| DEK per record or object | Envelope encryption | Limit never binds | KMS calls (cache them) |
| XChaCha20-Poly1305 | 192-bit random nonces | Safe random nonces at volume | Not FIPS approved |
| AES-GCM-SIV | Misuse-resistant AEAD | Repeated nonce leaks only equality | Two passes over the data; fewer libraries |
| Count and rotate | Encryption counter per key, rotate before 2^32 | Works with plain GCM | State to keep correct across replicas |
Erasing one customer from immutable storage
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Crypto-shredding | Per-subject or per-tenant key, destroy it | Covers backups, replicas, logs | Key granularity designed up front |
| Tombstone + compaction | Kafka compacted topics, delete markers | Native for keyed topics | Does not reach backups |
| Backup expiry | Erasure completes when the last backup ages out | Simple | Weeks to months of delay |
KMS latency, cost and quotas
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Data-key caching | AWS Encryption SDK caching CMM, Tink, local LRU with TTL and use limits | Orders of magnitude fewer KMS calls | Plaintext keys in memory longer |
| One DEK per object, not per field | Encrypt a JSON document as a unit | Fewer keys | Coarser access control |
| Batch rewrap off-peak | Chunked jobs with rate limits | Avoids throttling | Slower rotation |
| Multi-region keys | AWS KMS multi-region keys, Cloud KMS multi-region locations | Local latency, DR | Key policy replicated across regions |
A compromised intermediate CA or signing key
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Two-tier PKI | Offline root signs a new intermediate | Root survives | Root ceremony |
| Short leaf lifetimes | Leaves from the old intermediate expire in hours or days | No revocation needed | Automation required |
| Trust bundle rollover | Distribute the new intermediate or root before switching | No outage | Planning |
| Transparency | CT monitoring, Rekor for signatures | Detects misuse | Monitoring effort |
Choosing
What to encrypt, where
| Data / situation | Layer | Key design | Reason |
|---|---|---|---|
| Every disk, volume, snapshot, bucket | Disk / SSE-KMS | Provider default keys or CMK | Free baseline against media loss |
| Card numbers, national ids, health notes | Field-level envelope | Per-tenant KEK in KMS, DEK per value, blind index if lookups | Stops injection, dumps, analysts |
| Free-text personal data in an event store | Field-level, per subject | Per-subject keys wrapped by tenant KEK | Crypto-shredding for erasure |
| Session cookies, signed URLs | Framework encrypter / HMAC | APP_KEY, rotated with previous keys | Built in, short-lived |
| Passwords | Not encryption: hashing | Argon2id | Must not be reversible |
| Search fields (name, address) | Disk + access control | n/a | Field encryption kills search; reduce access instead |
| Backups shipped to another account/region | Backup encryption with a separate KEK | KEK in the destination region | Isolates blast radius |
| Messages in Kafka with long retention | Payload envelope encryption | KEK per data class | Brokers and consumers without the key see ciphertext |
Which certificate source
| Endpoint | Source | Lifetime | Renewal |
|---|---|---|---|
| Public website / API | Let's Encrypt or a commercial CA via ACME, or AWS ACM | 90 days now, 47 by 2029 | cert-manager, Caddy, certbot, ACM |
| Origin behind a CDN | CDN origin CA or public CA | Long for origin CA (CDN-specific) | Provider |
| Internal HTTP/gRPC between services | Mesh CA (Istio, Linkerd) or SPIRE | Hours | Automatic |
| Databases, brokers | Private CA (step-ca, Vault PKI, AWS Private CA) | Days to months | Agent or cert-manager |
| Developer laptops | mkcert (see TLS in Practice) | Long | Manual, never in production |
Which secret store and injection
| Situation | Store | Injection | Rotation |
|---|---|---|---|
| AWS-only, RDS databases | AWS Secrets Manager | ECS secrets / ESO / SDK | Managed rotation |
| Multi-cloud, dynamic database users | Vault | Vault Agent sidecar | Leases |
| Kubernetes with GitOps | Vault or a cloud store + ESO; or SOPS/age, sealed-secrets | Files | Store-driven or re-seal |
| Small Laravel app on one VM | Cloud secret store or env:encrypt | Rendered .env at deploy, config:cache | Manual, scheduled |
| CI/CD access to clouds | No stored secret: OIDC federation | Short-lived tokens | Automatic |
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:
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 leaseThe 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)
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)
go run ./before
# nonce a: 000000000000000000000001
# nonce b: 000000000000000000000001
# same nonce, same key: trueExperiment 3: the test suite, with NIST and RFC vectors (run)
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/tlsconfigExperiment 4: inspect a real chain and TLS policy (expected, not run)
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)
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)
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)
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
| Belief | Reality |
|---|---|
| "Encrypted at rest" means protected from attackers | Disk and TDE protect media and files; anyone who can query the database sees plaintext |
| RSA is for encrypting data | Public-key crypto agrees on or wraps symmetric keys; AEADs encrypt data |
| AES-256-CBC is the strongest choice | Without a MAC it is malleable and vulnerable to padding oracles; use an AEAD |
| Random nonces never collide | The birthday bound: NIST caps random-IV GCM at 2^32 messages per key |
| Key rotation re-encrypts the database | With envelope encryption it adds a KEK version; rewrap touches only wrapped DEKs |
| Rotating a key protects data that already leaked | Copied ciphertext stays decryptable with the old key until it is destroyed |
| Revocation will save us if a key leaks | Browsers barely check; Let's Encrypt ended OCSP; short lifetimes are the real control |
| The Common Name must match the host | Clients check the SAN; Go ignores the Common Name |
| Pinning the leaf certificate is best practice | With 47-day certificates it guarantees outages; OWASP recommends against pinning in nearly all cases |
| Environment variables are a secure secret store | They leak to children, dumps and debug pages; files or an agent are safer |
| Deleting the commit removes a leaked key | History, clones and scrapers keep it; revoke and rotate |
| A signature proves the artefact is safe | It proves who signed; provenance and admission policy make it a control |
| We use AWS, so we are FIPS compliant | Provider attestations cover the provider; your modules and modes are yours to prove |
Laravel's APP_KEY rotation is automatic once APP_PREVIOUS_KEYS is set | Old values stay under the old key until rewritten; remove the old key only after re-encryption |
Cheat sheet
| Topic | Remember |
|---|---|
| Data encryption | AES-256-GCM or ChaCha20-Poly1305; XChaCha20 for random nonces at volume |
| Key agreement / signatures | X25519; Ed25519, ECDSA P-256 under FIPS, RSA-PSS if RSA |
| Derivation / integrity | HKDF-SHA-256 per purpose; HMAC-SHA-256 with constant-time compare |
| Avoid | ECB, CBC without MAC, PKCS#1 v1.5 encryption, MD5/SHA-1, custom crypto |
| Nonce limit | 2^32 random 96-bit IVs per key (SP 800-38D); DEK per record removes the problem |
| Envelope | DEK per value, KEK in KMS, store wrapped DEK + KEK id + version + nonce + ct |
| Rotation | New KEK version; rewrap; raise min decryption version; then destroy |
| Erasure | Crypto-shredding with keys at the granularity of deletion |
| At rest | Disk < TDE < field-level; pick by threat; blind index for exact match only |
| In transit | TLS 1.2+ AEAD only, TLS 1.3 preferred; verify certificates on every internal hop |
| Certificates | 200 days (2026), 100 (2027), 47 (2029); automate, monitor CT, CAA |
| Revocation | CRL; OCSP being retired; short-lived certificates as the real answer |
| Private PKI | Offline root, online intermediate; step-ca, Vault PKI, AWS Private CA; SPIFFE IDs |
| Secrets | One store, workload identity, files or agent, dynamic where possible, scan every commit |
| Laravel | APP_PREVIOUS_KEYS + re-encrypt; encrypted casts need TEXT; env() only in config |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — 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
| Term | Meaning |
|---|---|
| Symmetric encryption | One shared key encrypts and decrypts (AES, ChaCha20) |
| Asymmetric encryption | A public/private key pair; used for key agreement, signatures and wrapping small values |
| AEAD | Authenticated Encryption with Associated Data: confidentiality plus integrity of ciphertext and AAD |
| AAD | Associated data: authenticated, not encrypted (row id, tenant, table) |
| AES-256-GCM | AES with a 256-bit key in Galois/Counter Mode; the default AEAD |
| ChaCha20-Poly1305 | Stream-cipher AEAD from RFC 8439; fast without AES hardware |
| XChaCha20 | ChaCha20 variant with a 192-bit nonce, safe for random nonces at volume |
| AES-GCM-SIV | Nonce-misuse-resistant AEAD (RFC 8452) |
| Nonce | Number used once per encryption under a key |
| IV | Initialization vector; GCM's name for its nonce |
| Nonce reuse | Using the same nonce twice under one key; catastrophic for GCM and ChaCha20-Poly1305 |
| X25519 | ECDH key agreement over Curve25519 (RFC 7748) |
| ECDH | Elliptic-curve Diffie-Hellman key agreement |
| X25519MLKEM768 | Hybrid classical + post-quantum key exchange, Go's TLS default since 1.24 |
| Ed25519 | EdDSA signatures over Curve25519 (RFC 8032) |
| ECDSA | Elliptic-curve signatures, usually over P-256; FIPS approved |
| RSA-PSS | Probabilistic RSA signature padding |
| RSA-OAEP | RSA encryption padding that resists chosen-ciphertext attacks |
| RSA PKCS#1 v1.5 | Legacy RSA padding; its encryption mode is vulnerable to Bleichenbacher attacks |
| HKDF | HMAC-based key derivation (RFC 5869): extract, then expand per purpose |
| HMAC | Keyed hash MAC; HMAC-SHA-256 for integrity with a shared key |
| SHA-256 | SHA-2 hash with a 256-bit output |
| MD5, SHA-1 | Broken hash functions; collisions are practical |
| Argon2id | Memory-hard password hash (RFC 9106) |
| ECB | Block mode that encrypts equal blocks identically; never use |
| CBC | Block mode needing a MAC; without one it is malleable |
| Padding oracle | An error difference that lets an attacker decrypt CBC ciphertext |
| Custom crypto | Home-made algorithms or protocols; do not |
| Envelope encryption | Data encrypted with a DEK; the DEK encrypted with a KEK |
| DEK | Data encryption key; fresh per value or object |
| KEK | Key encryption key; wraps DEKs, stays in the KMS |
| KMS | Key management service (AWS KMS, Cloud KMS, Azure Key Vault, Vault Transit) |
| Root key | The top of the hierarchy, kept in an HSM |
| Key hierarchy | Tree of keys, each level protecting the one below |
| Key rotation | Creating a new key version for new encryptions |
| Re-wrap | Re-encrypting a wrapped DEK under a new KEK version without exposing it |
| min_decryption_version | Vault Transit setting that refuses older key versions |
| Encryption context | AWS KMS name for AAD bound to a data key, logged in CloudTrail |
| Data-key caching | Reusing a plaintext DEK briefly to save KMS calls |
| Crypto-shredding | Deleting data by destroying the key that encrypts it |
| HSM | Hardware security module: keys generated and used inside tamper-resistant hardware |
| FIPS 140-3 | US/Canadian standard for validating cryptographic modules |
| CMVP | NIST program that validates modules under FIPS 140-3 |
| GOFIPS140 | Go build setting selecting the FIPS 140-3 Go Cryptographic Module |
| Cryptoperiod | Time a key is authorized for use (NIST SP 800-57) |
| Encryption at rest | Protection of stored data: disk, TDE, field-level |
| TDE | Transparent data encryption inside the database engine |
| Field-level encryption | Application encrypts values before storing them |
| Searchable encryption | Techniques that keep some query ability over ciphertext |
| Deterministic encryption | Same plaintext gives same ciphertext; leaks equality |
| Convergent encryption | Vault Transit's deterministic mode |
| Blind index | Keyed HMAC of a normalized value for exact-match lookup |
| Tokenisation | Replacing sensitive values with tokens held in a vault |
| Encryption in transit | Protecting data on the network, normally with TLS |
| TLS 1.3 | RFC 8446; AEAD-only, forward secrecy always |
| Cipher suite | The algorithm set a TLS connection uses |
| Forward secrecy | Past sessions stay safe if a long-term key leaks later |
| 0-RTT | TLS 1.3 early data; replayable, idempotent requests only |
| TLS termination | Where a TLS connection ends and plaintext exists |
| TLS passthrough | Load balancer forwards encrypted bytes; backend terminates |
| HSTS | Header telling browsers to use HTTPS only |
| mTLS | Mutual TLS: both sides present certificates |
| Certificate pinning | Client accepts only a specific certificate or key |
| PKI | Public key infrastructure: CAs, certificates, revocation, trust stores |
| Certificate authority | Entity that signs certificates |
| Root CA | Self-signed CA in trust stores, kept offline |
| Intermediate CA | CA signed by the root that issues leaves |
| Chain | Leaf, intermediates and root forming a validation path |
| CSR | Certificate signing request (PKCS#10) |
| SAN | subjectAltName extension listing the names a certificate is valid for |
| EKU | Extended key usage: serverAuth, clientAuth, codeSigning |
| Validity period | notBefore to notAfter |
| CRL | Certificate revocation list |
| OCSP | Online Certificate Status Protocol (RFC 6960) |
| OCSP stapling | Server attaches a fresh OCSP response in the handshake |
| Short-lived certificate | Certificate short enough that revocation is unnecessary |
| Certificate Transparency | Public append-only logs of issued certificates (RFC 6962) |
| SCT | Signed certificate timestamp, proof of CT logging |
| CAA | DNS record restricting which CAs may issue for a domain |
| ACME | Automated Certificate Management Environment (RFC 8555) |
| Let's Encrypt | Free public ACME CA |
| http-01, dns-01, tls-alpn-01 | ACME challenge types |
| Private PKI | A CA hierarchy you run for internal names and workloads |
| step-ca | smallstep's online private CA with ACME and OIDC provisioners |
| Vault PKI | HashiCorp Vault secrets engine that issues certificates |
| cert-manager | Kubernetes controller that issues and renews certificates |
| SPIFFE | Standard for workload identity (spiffe:// IDs) |
| SPIRE | Reference implementation of SPIFFE |
| SVID | SPIFFE Verifiable Identity Document (X.509-SVID, JWT-SVID) |
| Trust bundle | Set of CA certificates a workload trusts for a trust domain |
| Secrets management | Centralised storage, access, audit and rotation of secrets |
| Vault | HashiCorp's secrets manager (KV, dynamic secrets, PKI, transit) |
| Secrets Manager | AWS managed secrets store with rotation |
| Parameter Store | AWS Systems Manager parameters, SecureString via KMS |
| Secret Manager | Google Cloud's managed secrets store |
| Azure Key Vault | Azure store for secrets, keys and certificates |
| sealed-secrets | Bitnami controller decrypting secrets sealed to a cluster key |
| External Secrets Operator | Kubernetes operator syncing external stores into Secrets |
| SOPS | Tool encrypting values in YAML/JSON/ENV files with age, PGP or KMS |
| age | Small file encryption tool and format with X25519 recipients |
| Dynamic secrets | Credentials generated on request, with a lease |
| Lease | Vault metadata with TTL and renewability attached to a dynamic secret |
| Secret rotation | Replacing a secret on a schedule or after an incident |
| Secret injection | How a secret reaches a process: env, file, sidecar, API |
| Sidecar | Helper container next to the app (Vault Agent, Envoy) |
| Workload identity | Credentials derived from what the workload is (IAM role, SPIFFE ID) |
| Secret sprawl | Uncontrolled spread of secrets across systems |
| gitleaks | Pattern-based secret scanner for git and directories |
| trufflehog | Secret scanner with live verification of found credentials |
| Sigstore | Signing infrastructure: Fulcio CA, Rekor log |
| cosign | Sigstore's tool to sign and verify containers and blobs |
| Rekor | Sigstore transparency log for signatures |
| SLSA | Supply-chain Levels for Software Artifacts, build levels L0 to L3 |
| CSPRNG | Cryptographically secure random number generator |
| crypto/rand | Go's CSPRNG package (Read, Text) |
| random_bytes | PHP's CSPRNG function |
| APP_KEY | Laravel's application encryption key |
| APP_PREVIOUS_KEYS | Laravel's comma-separated list of old keys accepted for decryption |
| Encrypted cast | Eloquent cast that encrypts an attribute with Crypt |
| Crypt | Laravel facade for the encrypter |
| config:cache | Laravel command that caches configuration; .env is not loaded afterwards |
References
- AWS KMS cryptography essentials (envelope encryption): https://docs.aws.amazon.com/kms/latest/developerguide/kms-cryptography.html
- AWS KMS concepts: https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html
- AWS KMS GenerateDataKey: https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html
- AWS KMS Decrypt: https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html
- AWS KMS ReEncrypt: https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html
- AWS KMS key rotation: https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html
- AWS SDK for PHP, KMS examples: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/kms-example-encrypt.html
- AWS Secrets Manager: https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html
- AWS Secrets Manager rotation: https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html
- AWS Systems Manager Parameter Store: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html
- Google Cloud KMS, envelope encryption: https://cloud.google.com/kms/docs/envelope-encryption
- Google Cloud Secret Manager overview: https://cloud.google.com/secret-manager/docs/overview
- HashiCorp Vault Transit: https://developer.hashicorp.com/vault/docs/secrets/transit
- HashiCorp Vault PKI: https://developer.hashicorp.com/vault/docs/secrets/pki
- HashiCorp Vault leases: https://developer.hashicorp.com/vault/docs/concepts/lease
- HashiCorp Vault database secrets engine: https://developer.hashicorp.com/vault/docs/secrets/databases
- HashiCorp Vault Agent: https://developer.hashicorp.com/vault/docs/agent-and-proxy/agent
- HashiCorp Vault KV v2 API: https://developer.hashicorp.com/vault/api-docs/secret/kv/kv-v2
- HashiCorp Vault database API: https://developer.hashicorp.com/vault/api-docs/secret/databases
- NIST SP 800-38D (GCM): https://csrc.nist.gov/pubs/sp/800/38/d/final
- NIST CAVP GCM test vectors: https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/cavp-testing-block-cipher-modes
- NIST SP 800-57 Part 1 Rev. 5: https://csrc.nist.gov/pubs/sp/800/57/pt1/r5/final
- NIST SP 800-130: https://csrc.nist.gov/pubs/sp/800/130/final
- NIST SP 800-175B Rev. 1: https://csrc.nist.gov/pubs/sp/800/175/b/r1/final
- FIPS 140-3: https://csrc.nist.gov/pubs/fips/140-3/final
- RFC 8439 (ChaCha20-Poly1305): https://www.rfc-editor.org/rfc/rfc8439.txt
- XChaCha20 draft: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha
- RFC 8452 (AES-GCM-SIV): https://www.rfc-editor.org/rfc/rfc8452.txt
- RFC 7748 (X25519): https://www.rfc-editor.org/rfc/rfc7748.txt
- RFC 8032 (Ed25519): https://www.rfc-editor.org/rfc/rfc8032.txt
- RFC 5869 (HKDF): https://www.rfc-editor.org/rfc/rfc5869.txt
- RFC 8017 (RSA, OAEP, PSS): https://www.rfc-editor.org/rfc/rfc8017.txt
- RFC 9106 (Argon2): https://www.rfc-editor.org/rfc/rfc9106.txt
- RFC 8446 (TLS 1.3): https://www.rfc-editor.org/rfc/rfc8446.txt
- RFC 5280 (X.509 profile): https://www.rfc-editor.org/rfc/rfc5280.txt
- RFC 6960 (OCSP): https://www.rfc-editor.org/rfc/rfc6960.txt
- RFC 6962 (Certificate Transparency): https://www.rfc-editor.org/rfc/rfc6962.txt
- RFC 8555 (ACME): https://www.rfc-editor.org/rfc/rfc8555.txt
- RFC 8737 (ACME tls-alpn-01): https://www.rfc-editor.org/rfc/rfc8737.txt
- CA/Browser Forum TLS Baseline Requirements: https://cabforum.org/working-groups/server/baseline-requirements/requirements/
- CA/Browser Forum Ballot SC-081v3: https://cabforum.org/2025/04/11/ballot-sc081v3-introduce-schedule-of-reducing-validity-and-data-reuse-periods/
- Let's Encrypt, Ending OCSP Support in 2025: https://letsencrypt.org/2024/12/05/ending-ocsp/
- Let's Encrypt, six-day and IP address certificates: https://letsencrypt.org/2025/01/16/6-day-and-ip-certs/
- Let's Encrypt chains of trust: https://letsencrypt.org/certificates/
- Certificate Transparency, how CT works: https://certificate.transparency.dev/howctworks/
- Server-Side TLS guidelines (TLSRef, formerly Mozilla): https://docs.tlsref.org/server-side-tls.html
- NGINX
ngx_http_ssl_module: https://nginx.org/en/docs/http/ngx_http_ssl_module.html - cert-manager: https://cert-manager.io/docs/
- smallstep step-ca: https://smallstep.com/docs/step-ca/
- SPIFFE concepts: https://spiffe.io/docs/latest/spiffe-about/spiffe-concepts/
- SPIFFE standard: https://raw.githubusercontent.com/spiffe/spiffe/main/standards/SPIFFE.md
- X509-SVID standard: https://raw.githubusercontent.com/spiffe/spiffe/main/standards/X509-SVID.md
- Sigstore overview: https://docs.sigstore.dev/about/overview/
- cosign signing overview: https://docs.sigstore.dev/cosign/signing/overview/
- SLSA v1.0 levels: https://slsa.dev/spec/v1.0/levels
- OWASP Cryptographic Storage Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html
- OWASP Secrets Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
- OWASP Transport Layer Security Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html
- OWASP Certificate and Public Key Pinning: https://owasp.org/www-community/controls/Certificate_and_Public_Key_Pinning
- Kubernetes Secrets: https://kubernetes.io/docs/concepts/configuration/secret/
- Kubernetes, encrypting data at rest: https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/
- PostgreSQL encryption options: https://www.postgresql.org/docs/current/encryption-options.html
- External Secrets Operator: https://external-secrets.io/latest/
- Bitnami sealed-secrets: https://github.com/bitnami-labs/sealed-secrets
- SOPS: https://getsops.io/docs/
- age: https://github.com/FiloSottile/age
- gitleaks: https://github.com/gitleaks/gitleaks
- TruffleHog: https://github.com/trufflesecurity/trufflehog
- Go
crypto/cipher: https://pkg.go.dev/crypto/cipher - Go
crypto/tls: https://pkg.go.dev/crypto/tls - Go
crypto/rand: https://pkg.go.dev/crypto/rand - Go
crypto/hkdf: https://pkg.go.dev/crypto/hkdf - Go
crypto/ecdh: https://pkg.go.dev/crypto/ecdh - Go
crypto/ed25519: https://pkg.go.dev/crypto/ed25519 - Go
x/crypto/chacha20poly1305: https://pkg.go.dev/golang.org/x/crypto/chacha20poly1305 - Go FIPS 140-3 compliance: https://go.dev/doc/security/fips140
- PHP
random_bytes: https://www.php.net/manual/en/function.random-bytes.php - Laravel 13 Encryption: https://laravel.com/docs/13.x/encryption
- Laravel 13 Eloquent mutators and casts (encrypted casting): https://laravel.com/docs/13.x/eloquent-mutators
- Laravel 13 Configuration (config:cache, env:encrypt): https://laravel.com/docs/13.x/configuration
- Laravel 13 Deployment: https://laravel.com/docs/13.x/deployment
- Laravel 13 Migrations (binary columns): https://laravel.com/docs/13.x/migrations
- Laravel framework
Encrypter.php(13.x): https://raw.githubusercontent.com/laravel/framework/13.x/src/Illuminate/Encryption/Encrypter.php - Laravel skeleton
config/app.php(13.x): https://raw.githubusercontent.com/laravel/laravel/13.x/config/app.php