Encryption & secrets management

In one sentence

Encrypt data on the wire with TLS and on disk with keys held in a KMS, keep secrets in a vault as short-lived credentials, and store passwords only as slow, salted hashes.

Analogy: Each hotel guest's valuables sit in a room safe with its own key. All those keys stay locked in the manager's vault. Change the vault's lock and no room has to be emptied.

The data is encrypted locally with a one-off data key; only the small wrapped key travels to the KMS, which checks permissions and logs every use.

How it works

  • TLS 1.3 protects data in transit; mTLS also makes the client prove its identity with a certificate.
  • Envelope encryption: a per-object data key encrypts the data, and a KMS key encrypts that data key.
  • Store the wrapped data key beside the ciphertext; every decrypt is a permission-checked, logged KMS call.
  • Keep secrets in a secrets manager as short-lived credentials, never in code, images or logs.
  • Hash passwords with Argon2id and a per-user salt: hashing is one-way, encryption is not.

Check yourself

Answer to mark it learned; your answers aren't scored.

You must encrypt 2 GB video files under a customer's KMS key. The KMS Encrypt call rejects anything over 4,096 bytes. What is the right design?

Go deeper

Full explanation

Four separate jobs:

In transit. Run TLS 1.3 on every hop. Its public-key exchanges are forward-secret: stealing the server's key later does not decrypt recorded traffic. mTLS adds a client certificate, so both services prove who they are.

At rest. Encrypting is easy; protecting the key is the problem. Envelope encryption solves it: encrypt each object with its own data key (DEK), then encrypt that DEK with a key-encryption key (KEK) that never leaves the KMS. Store the wrapped DEK next to the ciphertext. Reading the data now requires a KMS call, which is permission-checked and logged. Rotating the KEK re-encrypts nothing: new writes use the new key material, and the old material stays to decrypt old data.

Secrets (database passwords, API keys, tokens). Keep them in a secrets manager and fetch them at runtime with the workload's identity. Never put them in code, images or logs. Prefer dynamic, short-lived credentials that expire on their own.

Passwords are hashed, not encrypted: a slow, salted, one-way hash such as Argon2id.

Who may use a key is authorization: see AuthN vs AuthZ: sessions, JWT, OAuth.

Code Envelope encryption with AWS KMS and AES-GCM
pythonEnvelope encryption with AWS KMS and AES-GCM
import os
import boto3
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

kms = boto3.client("kms")
KEK = "alias/app-data"   # key-encryption key: its material never leaves KMS

def encrypt(plaintext: bytes) -> dict:
    dk = kms.generate_data_key(KeyId=KEK, KeySpec="AES_256")
    nonce = os.urandom(12)            # must be unique per message for a GCM key
    ciphertext = AESGCM(dk["Plaintext"]).encrypt(nonce, plaintext, None)
    # Persist only the *wrapped* data key; the plaintext key dies with this call
    return {"ct": ciphertext, "nonce": nonce, "wrapped_key": dk["CiphertextBlob"]}

def decrypt(blob: dict) -> bytes:
    # IAM decides who may unwrap; every call lands in the audit log
    key = kms.decrypt(CiphertextBlob=blob["wrapped_key"])["Plaintext"]
    return AESGCM(key).decrypt(blob["nonce"], blob["ct"], None)
Real example

Assume a SaaS stores 50M customer documents in object storage. Calling KMS Encrypt on them is out: it accepts at most 4,096 bytes, and every read would be a round trip carrying the data.

With envelope encryption each document gets its own 256-bit data key; the app encrypts locally and stores the wrapped key in the object's metadata. One KMS key per tenant wraps that tenant's data keys. A leaked bucket yields only ciphertext, every unwrap is logged, and offboarding a tenant means deleting one key.

Trade-offs +3 · −3

+ You gain

  • A stolen disk, backup or bucket yields only ciphertext.
  • Central keys mean central control: one policy, one audit log, one place to revoke.
  • Short-lived credentials shrink the damage of a leak from months to minutes or hours.

− You pay

  • The KMS and the secrets manager become critical dependencies: when they are down, nothing decrypts.
  • Encryption at rest does not stop an attacker who steals the application's own credentials.
  • Expired certificates, failed rotations and deleted keys are new ways to cause an outage or lose data for good.

Use it when

Always: TLS on every hop, encryption at rest by default, a secrets manager from day one. Add envelope encryption with your own KMS keys for sensitive or per-tenant data, and mTLS between services.

Avoid it when

Don't invent ciphers or key formats: use the platform KMS and vetted libraries. Don't encrypt passwords: hash them. Don't encrypt fields in the app that you must search or index without a plan for it.

Numbers to know 5
  • TLS 1.3: RFC 8446 (August 2018), reissued with clarifications as RFC 9846 (July 2026). Static RSA key exchange removed, AEAD ciphers only, 1-RTT handshake; 0-RTT data can be replayed.
  • AWS KMS Encrypt takes at most 4,096 bytes, so bulk data needs a data key from GenerateDataKey.
  • AWS KMS automatic rotation (checked Nov 2026): every 365 days by default, configurable from 90 to 2,560 days; old key material is kept.
  • OWASP Password Storage Cheat Sheet (checked Nov 2026): Argon2id with at least 19 MiB of memory, 2 iterations, parallelism 1; legacy bcrypt at work factor 10 or more, 72-byte limit.
  • AWS STS role credentials (checked Nov 2026) last from 15 minutes to 12 hours, 1 hour by default.
Common pitfalls 4
  • Secrets in git, container images, CI logs or environment dumps in crash reports: assume they leaked and rotate them.
  • Fast hashes (MD5, SHA-256) for passwords: they are built for speed, so offline guessing is cheap.
  • TLS only up to the load balancer and plaintext inside the network, where an intruder moves next.
  • Long-lived static keys nobody dares rotate, because rotation was never automated or rehearsed.
Interview questions 3

Answer out loud first, then reveal.

Explain envelope encryption. Why not encrypt everything with the KMS key?Show answer

I encrypt each object with its own data key, and encrypt that data key with a key that never leaves the KMS. The wrapped data key is stored next to the ciphertext. Sending the data itself to the KMS doesn't scale: there is a size limit, a network round trip per operation, and all my data would transit the KMS. With envelopes, bulk encryption is local and fast, and rotating the master key doesn't mean re-encrypting the data.

A database password was committed to a public repo. What do you do, now and long term?Show answer

Now: treat it as compromised. I rotate the credential first, then check access logs for use, then clean the history; deleting the commit alone fixes nothing. Long term: secrets move to a secrets manager and are fetched at runtime by workload identity, static passwords become dynamic, short-lived database credentials, and secret scanning runs in pre-commit and CI. The goal is that the next leak expires before anyone can use it.

How do you store user passwords?Show answer

I never store or encrypt them. I store a hash from a slow, memory-hard function, Argon2id per current OWASP guidance, with a unique salt per user that the library generates. Slowness is the point: after a breach, every offline guess is expensive. I tune the parameters to a target login time on my hardware, rehash at login when I raise them, and can add a pepper kept outside the database.