Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Encrypt personal data and secrets in your database

An application stores customers’ emails and phone numbers, or the API tokens of their integrations, in its own tables. A copy of the database, a backup or a read-only replica leaks them, and so does anyone with a SQL console. Each field is encrypted under a DEK that a cloud KMS encrypts, with no keyring store. Every value carries its encrypted DEK, so nothing is stored apart from the values. For central rotation, deterministic fields across rotations or BigQuery reads across rotations, see Choosing a mode and the keyring.

Which mode

Values areModeSee
written rarely, such as secrets and configurationper-call envelopeEnvelope encryption
written at a high rate, or read repeatedlystore-less DEK reuse for writes, and a DEK cache for readsCut KMS calls with a DEK cache and DEK reuse
grouped, such as a file in chunks or a tenant’s rows, with one DEK the application keepsthe *_with_dek and *_with_encrypted_dek callsWorking with DEKs yourself
encrypted with a key the application holds, with no KMSAeadCipherAEAD without a KMS

The modes are compared in Choosing a mode.

The path

  1. A provider for the KMS, such as GcpKmsProvider::new(&key_ref), see KMS providers, with the rights of With kms-aead alone: decrypt for a reader, and encrypt too for a writer;
  2. KmsAeadEnvelope::new(provider), or with_options with a DekReusePolicy for store-less DEK reuse and a DekCache for repeated reads, see DEK caching and reuse;
  3. a newtype per field, such as Email, that implements Plaintext, and normalises the value if it is ever looked up, see Plaintext;
  4. the AAD that ties the value to its place, <table>/<row id>/<column>, so a value copied into another row fails to decrypt, see AAD;
  5. envelope.encrypt(aad, &value) into an Encrypted<Email, Envelope>, stored as a serde field, a BYTEA column through tokio-postgres or sqlx, or hex in a TEXT column, see Storing;
  6. envelope.decrypt(aad, &encrypted) with the same AAD, rebuilt from the row.

A first example, with the local KMS, is in With an envelope.

What to watch for