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 are | Mode | See |
|---|---|---|
| written rarely, such as secrets and configuration | per-call envelope | Envelope encryption |
| written at a high rate, or read repeatedly | store-less DEK reuse for writes, and a DEK cache for reads | Cut 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 keeps | the *_with_dek and *_with_encrypted_dek calls | Working with DEKs yourself |
| encrypted with a key the application holds, with no KMS | AeadCipher | AEAD without a KMS |
The modes are compared in Choosing a mode.
The path
- 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; KmsAeadEnvelope::new(provider), orwith_optionswith aDekReusePolicyfor store-less DEK reuse and aDekCachefor repeated reads, see DEK caching and reuse;- a newtype per field, such as
Email, that implementsPlaintext, and normalises the value if it is ever looked up, seePlaintext; - 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; envelope.encrypt(aad, &value)into anEncrypted<Email, Envelope>, stored as a serde field, aBYTEAcolumn through tokio-postgres or sqlx, or hex in aTEXTcolumn, see Storing;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
- The value does not record its algorithm, so the writer and the reader use the same one, see Envelope encryption;
- the AAD is not stored in the value, so every read rebuilds it from the row exactly as the write built it, see AAD;
- finding rows by an encrypted field needs a deterministic field or a beacon, see Find a user by an encrypted email;
- Tink reads envelope values on Cloud KMS and AWS KMS keys, and BigQuery does not, see Decrypt columns in BigQuery SQL or with Tink;
- the KEK rotates in the KMS, and the stored DEKs are encrypted again before the old version is disabled, see With kms-aead alone;
- values move to a keyring later with a sweep, see Move envelope values to a keyring.