All notes
Encryption5 min read

Encryption is not a function call. It is a lifecycle.

Calling Encrypt() takes one line. Living with what it wrote, for years, under keys that will one day have to change, takes a plan.

When I first wrote encryption code for our platform, I thought of it as a solved problem: pick a good algorithm, call the library, done. Most of what I have learned since is about everything around that call. Where the key lives. What happens to data written last year. What breaks on the day the key has to change.

This note covers the three places we encrypt or hash things (passwords, data at rest, and download links) and the lessons each one taught me.

Passwords: hash, never encrypt

Passwords are the one thing you should never be able to decrypt. We moved from PBKDF2 to Argon2id early on, using the Konscious library, with these parameters:

ParameterValueWhy
Memory64 MiBMemory-hard: makes GPU and ASIC cracking expensive
Iterations4Tuned so one login costs a fraction of a second on our server
Parallelism2Matches what the server can spare per request
Salt16 random bytesFrom the OS cryptographic generator, unique per user
Output32 bytesCompared with CryptographicOperations.FixedTimeEquals

Two details mattered more than the algorithm itself.

Constant-time comparison. A normal == on byte arrays stops at the first difference, and that timing difference is measurable. FixedTimeEquals always compares every byte.

Unknown accounts must cost the same. If the e-mail address does not exist, the obvious code returns immediately. Argon2 with 64 MiB takes noticeable time, so "fast answer" means "no such user", and an attacker can enumerate accounts with a stopwatch. We now run a dummy verification for unknown addresses, so a miss takes as long as a hit.

if (user is null)
{
    PasswordHasher.DummyVerify();   // burn the same time as a real check
    return InvalidCredentials();
}

We also check new passwords against the Have I Been Pwned database using its k-anonymity API: only the first five characters of the SHA-1 hash leave our server, and the full password never does.

The fixed IV I am not proud of

Our first general-purpose encryption helper used AES in CBC mode with a key and an IV that never changed. In the very first version, both were derived from a passphrase written in the source code.

A fixed IV means the same plaintext always produces the same ciphertext, which leaks patterns. A key in the source code means anyone who has ever cloned the repository has the key. Neither is a theoretical problem: both showed up in my own audit.

The fixes came in steps. The key moved to the environment. The IV became random per message and is stored in front of the ciphertext. Then we went further and moved to AES-256-GCM, because CBC has a second weakness: it gives you confidentiality but no integrity. Someone can flip bits in CBC ciphertext and you will happily decrypt garbage, or worse, something they chose. GCM adds an authentication tag, and decryption fails loudly if anything was touched.

Three generations of ciphertext

Here is the part nobody warns you about. When you improve an encryption scheme, the old data does not upgrade itself. Our document download links went through three formats: fixed-IV CBC, then random-IV CBC, then GCM. On any given day the database held all three.

Two things made that manageable.

A version prefix. New values at rest are written as g1: followed by the nonce, tag and ciphertext. Anything without the prefix is the older format. The reader knows what it is looking at without guessing.

public static string DecryptAtRest(string stored) =>
    stored.StartsWith("g1:")
        ? DecryptGcm(stored[3..])     // current format
        : DecryptLegacyCbc(stored);   // still readable, never written again

An explicit migration. Reading old formats forever is a trap; the old code path never dies. For download links we built an admin-only, idempotent endpoint that re-encrypts every stored link into the current format. Run it once after the deploy, run it twice and nothing changes. Only after that can the legacy reader and the old key be deleted.

Rule I keep nowEvery encrypted value carries a format marker from day one, even if there is only one format. The day you need a second one, you will be glad.

Rotating keys is the real test

The hardest part of the whole security project was not any single fix. It was the key rotation after we found real secrets in the git history: database passwords, the JWT signing key, the mail provider password, the storage account key. Once a secret has been committed, you have to assume it is known. Deleting the file does not help; the history keeps it, and pull-request references on the git host cannot even be force-pushed away.

So every key had to change. And every key had a different blast radius:

  • The JWT signing key: changing it logs every user out, once.
  • The storage account key: every existing download link was signed with it. Regenerate it carelessly and every link in every e-mail breaks. The order is: re-sign the links against the second key, switch the API to that key, then regenerate the first.
  • The data encryption key: it protected stored MFA secrets. Change it without re-encrypting them first, and every user with MFA has to enrol again.
  • Keys shared between the API and the portals: both sides must change in the same maintenance window, or nobody can log in.

I ended up writing a runbook with the exact order, a backup step, and a checklist to run afterwards: an admin login, an auditor login, a customer login, one MFA login, one document download, one password-reset e-mail. Writing that runbook taught me more about our architecture than building it did.

Where secrets live

Secrets now load from an environment file on the server that deployments never touch, with Azure Key Vault as an option. The front ends take theirs from CI secrets at build time. Logs redact tokens. Production builds strip console output, because we found one place that logged an encryption key "temporarily".

One subtle trap: a library that reads .env files may expand $ as a variable reference. A randomly generated secret that happens to contain a dollar sign gets silently truncated, and everything works until you move to a host that reads the file differently. Generate secrets from an alphabet without $, or quote them, and test the value your code actually receives.

What I would do differently

If I started again tomorrow
  • Store password hashes in PHC format ($argon2id$v=19$m=65536,t=4,p=2$…). Ours stored only salt and hash, so the parameters live in code. With the parameters in the string, you can raise them later and rehash on the next successful login.
  • One key per purpose. A key that protects login traffic should not also protect data at rest. If one leaks, the other should not.
  • Build key versioning before you need it: a key ID next to every ciphertext, and a reader that can hold two keys during a rotation.
  • Use GCM (or another AEAD mode) from the first line. There is no reason to start with CBC in 2026.
  • Never commit a secret, even "just for dev". The cleanup cost me more than any feature that year.