How it works
The explanation, with examples you can run.
In transit
Use TLS everywhere: browser to edge, edge to service, service to database, service to service. "It's on our private network" is not a reason to skip it; flat internal networks are exactly where attackers move after the first foothold. Mutual TLS adds authentication of the client service as well.
At rest: layers and what they stop
- Full-disk and volume encryption (cloud disks, laptops): protects lost or decommissioned hardware and raw snapshots. Transparent to anything running on the machine.
- Database or storage-service encryption (transparent data encryption, encrypted buckets): protects the files and backups; the service decrypts for any authorised query.
- Application-level (field-level) encryption: the app encrypts specific fields (a national ID, card data, health notes) before storing them, with keys the database never sees. A SQL injection or a stolen database dump then yields ciphertext. It costs you: you can't search or index those fields normally.
Turn on the first two by default; they are nearly free in the cloud. Use the third for the data whose leak would hurt most.
Envelope encryption and a KMS
Keeping keys in a config file next to the data defeats the point. The usual design is envelope encryption:
- A key management service (AWS KMS, Google Cloud KMS, Azure Key Vault, HashiCorp Vault Transit) holds a master key that never leaves it.
- To encrypt, you ask the KMS for a fresh data key. It returns the key in plain form and wrapped (encrypted under the master key).
- You encrypt the data locally with the plain data key, store the wrapped key next to the ciphertext, and discard the plain key.
- To decrypt, you send the wrapped key to the KMS, which unwraps it if your identity is allowed to.
Access to the master key is now an IAM policy you can audit, every use is logged, and rotating the master key doesn't mean re-encrypting all the data.
Using cryptography safely
- Use authenticated encryption: AES-256-GCM or ChaCha20-Poly1305. It detects tampering as well as hiding content.
- Use a high-level library (libsodium, Tink, your platform's standard crypto with recommended defaults). Never design your own scheme.
- Never reuse a nonce with the same key in GCM; let the library generate them.
- Get randomness from the OS's secure generator (
crypto.getRandomValues,secretsin Python), neverMath.random. - Plan rotation and record which key version encrypted what.
- Remember passwords are hashed, not encrypted (see the passwords topic).
Check yourself
3 questions. Get them all right to finish this topic.
0 of 3 right so far. Get all three to finish this topic.