Distributed patterns and operations

Encryption at rest and in transit

Match encryption to the threat it answers, explain TLS, mTLS and the layers of encryption at rest, and design key management with envelope encryption and rotation.

Lesson14 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A company keeps customer records in a database, writes nightly backups to object storage, and serves its site over HTTPS terminated at a load balancer. Consider three ways this goes wrong.

A backup bucket is made public by mistake. The backups are plain SQL dumps, so every record is readable by whoever finds the URL.

Someone with access to the internal network captures traffic between the load balancer and the app servers. That hop is plain HTTP, so they collect session cookies and personal data.

The team reacts by encrypting sensitive columns with an AES key. The key sits in a configuration file in the code repository. Every developer has a copy, and the same key is still in use five years later, because changing it would mean re-encrypting every row and nobody has planned for that.

Each failure is a different threat, and the third shows that encrypting data only moves the problem to the key. So every design should answer two questions: who must not be able to read this, and where does the key live?

Start from the threat model

In transit, the attacker sits on the network path and can read or alter packets. That includes the public internet and also your own network, where a compromised host or a curious insider may be listening. You need confidentiality, integrity and proof of who is at the other end.

At rest, the attacker obtains stored bytes without going through your application: a stolen or discarded disk, a leaked backup or snapshot, a misconfigured bucket, or an administrator of the storage layer.

Neither helps against an attacker who takes over the running application with valid credentials, because the application will decrypt for them. That threat is handled by access control and least privilege. See authentication and authorization.

The building blocks

Symmetric encryption uses one key to encrypt and decrypt. AES-256-GCM and ChaCha20-Poly1305 are the standard choices. They are fast enough for bulk data, and both are authenticated modes, which means tampering is detected. The hard part is getting the key to both sides safely.

Asymmetric cryptography uses a key pair. The public key verifies signatures or encrypts, and the private key signs or decrypts. RSA and elliptic curve schemes are far slower than symmetric ciphers, but they solve identity and key distribution.

Real systems combine them: asymmetric operations to authenticate and agree on a key, then symmetric encryption for the data.

Three terms are often confused:

Reversible? Use
Encoding (Base64) By anyone, no key Representation only, no security
Hashing (SHA-256) No Integrity checks, fingerprints
Encryption (AES-GCM) Only with the key Confidentiality

Passwords are a special case of hashing that needs a deliberately slow algorithm, covered in the authentication lesson.

In transit: TLS and mTLS

TLS is how nearly all traffic is encrypted in transit. The server presents a certificate signed by a certificate authority, the handshake authenticates it and agrees on fresh session keys, and the data then flows under a symmetric cipher. TLS 1.3 (2018) completes a full handshake in one round trip and dropped the older key exchanges that lacked forward secrecy. Session keys come from an ephemeral exchange, so stealing the server’s private key later does not decrypt recorded traffic.

The design questions are about where TLS ends.

  • Termination. TLS usually terminates at a CDN or load balancer. Beyond that point traffic is plaintext unless the load balancer opens a new TLS connection to the backend. Encrypt connections to databases, caches and message brokers too.
  • Mutual TLS (mTLS). The client also presents a certificate, so each side proves its identity. This is the common way to authenticate services to each other. A service mesh such as Istio or Linkerd issues short-lived certificates to each workload and rotates them automatically. mTLS proves who is calling. Deciding whether that caller is allowed is still a separate policy.
  • Cost. Handshakes add latency and CPU, which connection reuse largely removes. The larger cost is operating certificates, and an expired certificate is a classic cause of outages.

At rest: three layers

Layer Stops Does not stop
Disk or volume Stolen or discarded disks, raw access to storage Anyone who can log in to the host or database
Database (transparent data encryption) Theft of data files and encrypted backups Database users, SQL injection, administrators
Application or field level Administrators, SQL injection dumps, leaked replicas and exports Compromise of the application itself

The higher the layer, the more attackers it stops and the more it costs. A field encrypted by the application is opaque to the database, so it cannot be indexed, sorted or searched in the normal way. Equality lookups need a workaround such as a keyed hash of the value stored in a second column, which reveals when two rows hold the same value.

The usual answer is volume encryption everywhere, since it is nearly free and is the default on major clouds (Amazon S3 has encrypted all new objects by default since January 2023), plus application-level encryption for the few fields that justify it: government ids, health data, stored access tokens.

Envelope encryption and key management

Encryption turns a data problem into a key problem. Envelope encryption is the standard way to manage the key.

Envelope encryption with a key management service3 components: App service, KMS, Database. Connections: App service and KMS (wrap and unwrap keys); App service and Database (encrypted records).App serviceKMSholds the key encryption keykey never leavesDatabaseciphertext + wrapped keywrap and unwrap keysencrypted records

Step 1 of 8

An app must encrypt customer records before storing them. Sending every record to the key management service would be slow and costly, and the service only accepts small payloads. Envelope encryption uses two layers of keys instead.

Read the steps as text
  1. An app must encrypt customer records before storing them. Sending every record to the key management service would be slow and costly, and the service only accepts small payloads. Envelope encryption uses two layers of keys instead.
  2. The app asks the key management service for a new data key. The service returns two copies. One is the plaintext data key, and the other is the same key encrypted, or wrapped, under the key encryption key.
  3. The app encrypts the record locally with the plaintext data key, using a fast symmetric cipher such as AES-256-GCM. Then it erases the plaintext key from memory. Only the wrapped copy remains.
  4. The app stores the ciphertext and the wrapped data key side by side. Someone who steals the database or a backup gets both, but cannot unwrap the data key without calling the key management service.
  5. To read the record, the app fetches the ciphertext and the wrapped key, then asks the key management service to unwrap the key. The service checks the caller's permissions and writes an audit log entry before it answers.
  6. The app decrypts the record locally. It may cache the plaintext data key for a few minutes, so that a burst of reads does not need a call to the key management service for every record.
  7. To rotate, the service creates a new version of the key encryption key and wraps new data keys with it. Old wrapped keys can be unwrapped and wrapped again. Only these small keys are rewritten, and the terabytes of data stay as they are.
  8. Bulk data is encrypted locally with data keys, and the one key that protects them stays inside a hardened service with access control and an audit trail. That split makes encryption fast and rotation cheap.
Envelope encryption with a key management service

A data encryption key (DEK) encrypts the data locally. A key encryption key (KEK) inside a key management service (AWS KMS, Google Cloud KMS, Azure Key Vault, HashiCorp Vault) wraps the DEK. The KEK does not leave the service.

  • Bulk data never goes to the KMS. AWS KMS, for example, encrypts at most 4 KB directly.
  • Access policy and audit logs for all data live in one place.
  • A separate DEK per object, table or tenant limits what one leaked key exposes. Destroying a tenant’s key makes their data unreadable everywhere, including backups, which is called crypto-shredding.

The cost is that the KMS is now on your critical path, with latency, request quotas and a price per call. Cache data keys for a short time, and decide what happens when the KMS is unreachable.

Key rotation

Rotation limits how much data one key protects and how long a stolen key stays useful. Standards such as PCI DSS require it.

  • Rotating the KEK is cheap. The KMS creates a new version and uses it for new wrapping, and keeps old versions for decryption. With automatic rotation in AWS KMS, new key material is created on a schedule, yearly by default, and nothing has to be re-encrypted. You can re-wrap existing DEKs, which rewrites only small keys.
  • Rotating DEKs means re-encrypting data. Do it lazily when a record is next written, or with a background job. Store the key id and version beside each ciphertext so old and new keys work side by side.
  • After a compromise, rotation alone is not enough. Data encrypted under the leaked key must be re-encrypted and treated as exposed.

Secrets management

Database passwords, API keys, signing keys and TLS private keys are secrets. Keep them out of source code, container images and chat. Put them in a secrets manager such as HashiCorp Vault or AWS Secrets Manager, which gives encrypted storage, access tied to workload identity, an audit log and rotation. Prefer short-lived credentials issued on demand over static ones. Note that Kubernetes Secrets are only base64-encoded and are stored unencrypted in etcd unless you enable encryption at rest.

When to choose it and when not to

  • TLS on every external connection, and volume encryption at rest: always. They cost little.
  • mTLS between services: when you have many services and want verifiable service identity. A handful of services in a private network can start with server-side TLS and tokens.
  • Application-level encryption: only for fields where the threat justifies losing queryability. Encrypting every column this way makes the database nearly useless for queries.
  • Not encryption: for values you never need to read back, hash them. For access decisions, use authorization. And do not write your own cryptography. Use a vetted library such as libsodium or Tink.

In the interview

For most designs, two sentences are enough: TLS from clients to the edge and between services, storage encrypted at rest with keys in a KMS, sensitive fields encrypted at the application level with envelope encryption, and secrets in a secrets manager. Then move on.

Go deeper when the system handles payments, health data or private messages, or when asked. A strong minute names the threat each layer answers, explains envelope encryption, describes rotation without downtime using key versions, and admits what encryption does not cover: an attacker inside the running application.

Key takeaways

  • Start from the threat. Encryption in transit stops someone on the network path, and encryption at rest stops someone who obtains the storage without going through your application.
  • Symmetric ciphers are fast and encrypt the data. Asymmetric cryptography is slow and is used to prove identity and agree on symmetric keys.
  • Encryption at rest has layers: disk, database and application. Higher layers stop more attackers and cost more in queryability and complexity.
  • Envelope encryption encrypts data with a data key and wraps that key with a key held in a KMS, so bulk data never goes to the KMS and rotation rewrites only small keys.
  • Store a key id and version beside every ciphertext so that keys can be rotated without downtime.
  • Encoding is not security, hashing is one-way, and encryption is reversible with a key. Secrets belong in a secrets manager, not in code.

Check yourself

1. A database runs on encrypted cloud volumes. An attacker exploits SQL injection in the application. What does the volume encryption do for you?
2. Why does envelope encryption use two layers of keys instead of sending data to the KMS to be encrypted?
3. A team rotates its key encryption key in the KMS. What has to be rewritten?
4. A load balancer terminates TLS and forwards requests to app servers over plain HTTP. Which statement is accurate?
5. A developer stores API tokens in the database as Base64 strings "so they are not in plaintext". What is wrong?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What threat does encryption at rest address?

Someone obtaining the stored bytes without going through the application, such as a stolen disk, a leaked backup or snapshot, or a storage administrator. It does not stop an attacker using the running application.

Symmetric versus asymmetric encryption?

Symmetric uses one shared key and is fast, so it encrypts the data (AES-GCM). Asymmetric uses a key pair and is slow, so it is used for identity, signatures and key agreement.

What is mTLS?

Mutual TLS. The client presents a certificate as well as the server, so both ends are authenticated. It is the usual way to give services a verifiable identity.

What is envelope encryption?

Data is encrypted with a data key, and the data key is encrypted (wrapped) by a key encryption key held in a KMS. The wrapped key is stored next to the ciphertext.

Hashing versus encryption versus encoding?

Encoding is reversible by anyone and gives no security. Hashing is one-way. Encryption is reversible only with the key.

Why store a key version with each ciphertext?

So old data can still be decrypted after rotation, new data uses the new key, and re-encryption can happen gradually instead of in one risky migration.

Review the deck