Secrets management and encryption
Every application has secrets: database passwords, API keys, JWT signing keys, encryption keys, OAuth client secrets. Leaked secrets are one of the most common causes of breaches, and leaked keys pushed to public GitHub repositories are found and abused by bots within minutes. This lesson covers where secrets belong, and how to encrypt sensitive data properly.
Where secrets don't belong
- In source code, even "temporarily". Git remembers every version forever, including deleted lines.
- In front-end code or mobile apps: anything shipped to users can be extracted.
- In logs, error messages, URLs (
?api_key=…ends up in server and proxy logs), screenshots and tickets. - In Docker images (
ENV API_KEY=…is visible to anyone who can pull the image). - In chat messages and wikis.
const stripe = new Stripe('sk_live_51Hq…'); // ❌ committed to Git, visible to every developer, in every clone
const stripe = new Stripe(process.env.STRIPE_KEY); // ✅ injected at run timeLevels of secrets management
| Level | How | Good for |
|---|---|---|
| 1 | .env file, git-ignored, on each developer's machine |
Local development |
| 2 | Environment variables set in the hosting platform (Render, Fly, Vercel, Heroku, GitHub Actions secrets) | Small apps |
| 3 | A secrets manager: AWS Secrets Manager, Google Secret Manager, Azure Key Vault, HashiCorp Vault, Doppler, Infisical, 1Password | Teams and production systems |
| 4 | No long-lived secrets: workload identity (IAM roles, OIDC federation) and short-lived, automatically issued credentials | Mature cloud setups |
Secrets managers add access control (which service may read which secret), audit logs (who read it, when), versioning and automatic rotation. Level 4 is the goal: GitHub Actions deploying to AWS via OIDC needs no stored AWS key at all.
Prevent leaks before they happen
- Add
.env,*.pemand credential files to.gitignorefrom day one. - Run a secret scanner as a pre-commit hook and in CI: gitleaks, trufflehog, GitHub push protection.
- Use separate secrets per environment, so a leaked development key doesn't open production.
When a secret leaks
- Revoke and rotate it immediately: assume it's already been used. Deleting the commit is not enough (forks, clones and caches keep it).
- Check the provider's logs for abuse.
- Then clean the history if needed, and find out how it happened.
That's why rotation must be easy: support two valid keys at once (old and new), so you can switch without downtime.
Encryption basics
| Purpose | Reversible? | Examples | |
|---|---|---|---|
| Hashing | Fingerprints, password storage | ✖ | SHA-256, Argon2id |
| HMAC / signatures | Prove data wasn't changed (and who made it) | ✖ | HMAC-SHA256, Ed25519 |
| Symmetric encryption | Hide data; one key encrypts and decrypts | ✔ with the key | AES-256-GCM, ChaCha20-Poly1305 |
| Asymmetric encryption | Anyone can encrypt with the public key; only the private key decrypts | ✔ with the private key | RSA-OAEP, X25519 (in HPKE) |
Encoding is not encryption: base64 hides nothing.
Encrypting data with AES-256-GCM
Use authenticated encryption: it hides the data and detects any tampering. AES-256-GCM is the standard choice:
The additional authenticated data (user:42) binds the ciphertext to its owner: an attacker who copies an encrypted value into another user's row gets an error instead of data.
Rules for encryption
- Don't invent cryptography. Use AES-GCM or ChaCha20-Poly1305 through a standard library, or a higher-level one (libsodium, Google Tink) that makes mistakes hard.
- Never reuse an IV/nonce with the same key in GCM: it can reveal the key stream.
- Keys aren't passwords. Generate them with a secure random generator; if you must derive one from a password, use scrypt or Argon2.
- Keep keys away from the data: in a KMS (AWS KMS, Google Cloud KMS, Azure Key Vault) or HSM. Envelope encryption: encrypt each record with a data key, and encrypt that data key with a master key that never leaves the KMS.
- Plan for rotation: store a key ID with each ciphertext, so old data can be read while new data uses the new key.
Encryption in transit and at rest
- In transit: TLS everywhere: browser to load balancer, and service to database too (
sslmode=verify-fullfor PostgreSQL). - At rest: enable disk, database and backup encryption (usually one setting in the cloud). For especially sensitive fields (national ID numbers, health data), add application-level encryption as above, so even database administrators and leaked backups see only ciphertext.
- Minimise: the safest data is data you never store. Don't keep card numbers at all; let a payment provider tokenise them.
Practice
- Add a key ID to the encrypted format (
k1.iv.tag.ciphertext) and writedecryptso it picks the right key from{ k1: …, k2: … }. - Write a tiny secret scanner: report lines in a string that look like
sk_live_…orAKIAfollowed by 16 characters. - Describe the steps you'd take if a teammate pushed the production database password to a public repository.
1.A secret was committed to Git and the commit was deleted an hour later. What now?
2.Why use AES-GCM instead of plain AES-CBC or ECB?
3.What is envelope encryption?