Encryption at Rest, in Transit & in Use (TDE, Column, Homomorphic)
"If the system administrator for the server's machine cannot be trusted, it is necessary for the client to encrypt the data; this way, unencrypted data never appears on the database server." — PostgreSQL documentation, Encryption Options
Summary: Encryption protects data in three states (at rest, in transit, in use), and every layer defeats a different attacker: a stolen disk, a sniffed network, a curious DBA, a memory dump or the cloud provider itself. Focus: TDE and volume encryption, envelope encryption with KMS, TLS and sslmode, column and client-side encryption (searchable or not), blind indexes, confidential computing, homomorphic encryption, passwords versus encryption, masking, backups, performance, compliance and key loss. Learning goal: Name the attacker first, pick the cheapest layer that stops that attacker, design the key hierarchy so rotation and deletion are cheap, and know exactly which queries each choice breaks.
This page is the complete reference for encrypting a database in its three states: at rest (files, WAL, backups), in transit (the wire between client, pooler, primary and replica) and in use (while the engine or the CPU computes on it). It covers what PostgreSQL, MySQL InnoDB, SQL Server, Oracle, MongoDB, SQLite, CockroachDB and Redis really offer, how envelope encryption and KMS keep keys away from the data, how to search encrypted columns with a blind index, what confidential computing and homomorphic encryption can and cannot do, and the Go and Laravel code for the application-side parts. It deliberately does not re-teach its neighbour Database Security: authentication, roles, RLS, SQL injection, pg_hba.conf, the sslmode table with its man-in-the-middle timeline, secrets with Vault and audit logging live there, and this page links to them instead. Backups as a process are in Backup, PITR & Disaster Recovery, WAL internals in Durability, WAL & Crash Recovery, and multi-tenant isolation (a key per tenant) in Multi-Tenancy Strategies. The general cryptography primer is Cryptography in Practice.
Page map
| If you are looking for | Go to |
|---|---|
| Three tables you can memorise | Everything in one minute |
| Why encryption has layers, and the vault analogy | Why it exists |
| Who invented what, and which feature arrived when | Where it comes from |
| Which attacker each layer stops | Threat model per layer |
| LUKS, EBS/RDS, TDE in SQL Server, Oracle, MySQL, MongoDB; PostgreSQL has none | Encryption at rest |
| DEK, KEK, envelope encryption, KMS, HSM, rotation, key loss, crypto-shredding | Keys and key hierarchy |
TLS 1.2/1.3, sslmode, mTLS, replication, PgBouncer | Encryption in transit |
pgcrypto, deterministic vs randomised, blind index, tokenization, FPE | Column and application-level encryption |
| MongoDB CSFLE and Queryable Encryption, SQL Server Always Encrypted | Client-side field-level encryption |
| SEV-SNP, TDX, SGX, attestation, PHE/SHE/FHE | Encryption in use |
| Passwords, argon2id, bcrypt, dynamic data masking | Hashing, passwords and masking |
| Backups, WAL, temp files, performance and AES-NI | Backups, WAL and cost |
| PCI DSS, GDPR, HIPAA mapped to layers | Compliance mapping |
| Engine by engine, knobs, error messages | Per-engine behaviour, Mechanics |
| Fixes with SQL, Go and Laravel | Solving the classic problems |
| Which layer for which situation | Choosing |
| Monolith to microservices to multi-region | In architecture |
Reproduce it: pgcrypto, blind index, sslmode, Laravel cast | Lab |
Everything in one minute
The layers. Each row is unpacked in its own section.
| Layer | What is encrypted | Who holds the key | Stops | Does not stop |
|---|---|---|---|---|
Volume / disk (LUKS, dm-crypt, EBS, RDS storage) | Every block, below the file system | OS, or the cloud KMS | Stolen disk, discarded hardware | Anyone logged in to the running server, a stolen database login |
TDE (SQL Server, Oracle, MySQL InnoDB, MongoDB Enterprise, pg_tde) | Data files, log, often backups | The engine, with a master key in a keystore or KMS | Stolen files and backup media | A DBA who can run SELECT |
TLS (sslmode=verify-full, require_secure_transport) | Bytes on the wire | The two endpoints' certificates | Sniffing, man-in-the-middle | Anything once the data reaches the server |
Column encryption in the database (pgcrypto) | Chosen columns | A key the client sends to the server | Casual readers of the table | A root user who watches the server, logs and memory |
Application or client-side field encryption (Laravel encrypted, Always Encrypted, CSFLE) | Chosen fields, before the database sees them | The application, backed by a KMS | DBA, backup thief, cloud operator | A compromised application server |
| Confidential computing (SEV-SNP, TDX, SGX) | Memory of a VM or enclave while running | The CPU | Host admin, hypervisor, memory dump | Bugs inside the protected code, side channels |
| Homomorphic encryption (PHE, SHE, FHE) | Values, even while computed on | The data owner | The server learns nothing | Cost: slow, large, limited operations |
The words people mix up.
| Term | One-line meaning | Reversible? | Typical use |
|---|---|---|---|
| Encryption | Scramble with a key; the key unscrambles | Yes, with the key | Card numbers, national IDs, tokens |
| Hashing | One-way fingerprint | No | Passwords (slow hashes), integrity checks |
| HMAC | Hash with a secret key | No | Blind index, signatures of cookies |
| Encoding (Base64, hex) | Change the alphabet, no secret | Yes, by anyone | Storing bytes as text |
| Tokenization | Replace a value with a random token; the mapping lives in a vault | Yes, through the vault | PCI card numbers |
| Masking | Show a fake or partial value | Not from the mask | Non-production copies, support screens |
| Pseudonymisation | Replace identifiers so the person is not directly identifiable (GDPR Art. 4 and 32) | With extra information kept apart | Analytics |
What each choice does to queries.
| Choice | Equality = | Range, ORDER BY | LIKE | Joins | Cost |
|---|---|---|---|---|---|
| Volume or TDE | Normal | Normal | Normal | Normal | Small and constant |
| Randomised application encryption | No (needs a blind index) | No | No | No | You search elsewhere |
| Deterministic encryption | Yes (same ciphertext) | No | No | Equality joins | Leaks equal values |
| Blind index next to randomised ciphertext | Yes | No | No | Equality only | One extra indexed column |
| Order-preserving or enclave schemes | Yes | Yes (enclave) | Yes (enclave) | Yes | Special hardware or weaker secrecy |
| Homomorphic | Only supported arithmetic | Hard | Hard | Hard | Very high |
Why it exists
A database is a pile of files that a running program decrypts for anyone it trusts. Every attack on stored data is therefore an attack on one of three moments: the data sits somewhere (disk, backup, snapshot), the data moves (client to server, primary to replica), or the data is being used (loaded into RAM and read by the engine). One mechanism cannot cover all three, because each moment has a different place where the key must exist. The trade-off is always the same: the closer the key is to the data, the easier the system works and the less the encryption protects.
| Key close to the engine (transparent) | Key far from the engine (client-side) |
|---|---|
| Zero application change | Application and queries change |
| Every SQL feature keeps working | Search, sort, join, aggregate break or need tricks |
| Protects files and media | Protects against the DBA and the provider too |
| A DBA or a stolen login reads plaintext | Engine, backup and replica see only ciphertext |
| Cheap to operate | Key management becomes your problem |
The analogy we reuse on this page: a bank. The vault door is volume and TDE encryption: it matters when the whole building is carted away, and it is open all day because the clerks need the money. The armoured van is TLS: it matters while the money travels. The sealed envelope with the customer's own seal is client-side field encryption: even the branch manager who has the vault keys cannot read it. The vault keys in a different building, handed out against a signed slip is the KMS. And a private room where clerks count notes under a one-way mirror is confidential computing.
Three common misunderstandings, up front
- “The database is encrypted, so a SQL injection or a stolen password only gets ciphertext.” No. TDE and volume encryption are transparent: the engine decrypts for every authorised session, including the attacker's. They protect media, not logins.
- “We use HTTPS, so the database traffic is safe.” HTTPS covers browser to web server. The hop from application to database is a separate TLS connection with its own
sslmode, and libpq's defaultpreferdoes not even verify the server. - “Encryption and hashing are the same thing, just different strength.” Encryption is reversible by design; passwords must never be reversible. Passwords are hashed with a slow, salted algorithm (argon2id, bcrypt), never encrypted.
Where it comes from
Encryption in databases grew in the order the attackers appeared. First came the stolen tape or disk: Oracle, SQL Server and later MySQL added Transparent Data Encryption, where the engine encrypts pages as it writes them. The current docs describe it plainly; Microsoft: "TDE does real-time I/O encryption and decryption of data and log files." Next came the insider and the provider: Always Encrypted (SQL Server 2016 and Azure SQL Database, from 2015) moved the key to the client, MongoDB added Client-Side Field Level Encryption and then Queryable Encryption, and SQL Server 2019 added secure enclaves so some computation could happen on encrypted data inside protected memory. The newest layer is confidential computing: AMD SEV-SNP, Intel TDX and Intel SGX encrypt memory in use, and cloud providers sell it as Confidential VMs.
PostgreSQL is the odd one out. Its manual's Encryption Options page lists password hashing, column encryption with pgcrypto, file-system or block-level encryption, SSL and GSSAPI on the network, host authentication and client-side encryption, but no built-in TDE. A transparent data encryption feature was proposed on pgsql-hackers (the PostgreSQL wiki keeps the design notes on buffers, WAL, temporary files, backups and initialization vectors), it is not in core, and Percona ships an extension, pg_tde, that works only with Percona Server for PostgreSQL.
Two standards frame the vocabulary. NIST SP 800-57 (key management) defines the cryptoperiod: "the time span during which a specific key is authorized for use by legitimate entities", and it argues that limiting it limits the data available for cryptanalysis. NIST SP 800-38D defines GCM, the authenticated mode used almost everywhere now; it requires that, with random 96-bit IVs, the total number of invocations of the authenticated encryption function for one key "shall not exceed 2^32". Go's crypto/cipher documentation repeats the same limit for NewGCMWithRandomNonce. These numbers explain why the page insists on a data key per record or per batch and not one key for everything.
Threat model per layer
Start from the attacker, not from the feature. The picture marks, for each layer, which of six attackers it stops.
| Attacker | What they can get | Layers that help | Layers that do not |
|---|---|---|---|
| Disk or server thief, discarded drive | Raw blocks of the data directory | Volume encryption, TDE | TLS, RLS, roles |
| Backup leak (a public bucket, a stolen tape, a dump on a laptop) | A full copy of the data, often outside every access control | Backup encryption, TDE (engine backups), client-side keys | Volume encryption of the production server (the backup leaves it) |
| Network sniffer or man-in-the-middle | Queries, results, sometimes passwords | TLS verify-full, mTLS | Everything at rest |
| DBA or OS root insider | Anything the engine can read, the server's memory, the logs, pg_read_server_files | Client-side field encryption, separation of duties, audit (Database Security) | TDE, volume encryption, server-side pgcrypto |
| Memory dump or cold-boot attacker | Keys and plaintext pages in RAM | Confidential computing, short key lifetimes, no swap | TDE (pages are decrypted in the buffer pool) |
| Cloud provider operator, hypervisor, subpoena | Everything running on their hosts | Client-side keys held by you (HYOK), confidential computing with attestation | Provider-managed disk keys alone |
| Compromised application | Whatever the application can decrypt | Least privilege, per-tenant keys, audit | All the layers above |
The last row is the one people forget. If the application holds the key and the application is breached, the attacker holds the key too. Client-side encryption moves the trust boundary to the application; it does not remove it.
Encryption at rest
Volume and disk encryption Must-know
In plain words: the operating system or the cloud encrypts every block before it reaches the disk and decrypts it on the way back. The database never knows.
Common misunderstanding: “Our disks are encrypted, so a leaked backup file is safe.” A backup written to a mounted, decrypted file system is plaintext the moment it is copied off. PostgreSQL's manual says it directly: this mechanism "prevents unencrypted data from being read from the drives if the drives or the entire computer is stolen. This does not protect against attacks while the file system is mounted."
Definition: block-level (full-disk) encryption such as dm-crypt + LUKS on Linux, geli on FreeBSD, BitLocker on Windows, or file-system level such as eCryptfs and EncFS. In clouds it is a volume flag: Amazon RDS encrypted DB instances use "the industry standard AES-256 encryption algorithm" and also encrypt "backups, read replicas, and snapshots", with keys in AWS KMS, with, in the docs' words, "a minimal impact on performance".
Server boots Attacker with the stolen server / disk
1 unlock LUKS volume (passphrase, TPM or KMS)
2 mount /var/lib/postgresql -> plaintext view power off, pull the disk
3 postgres reads and writes normally read raw blocks -> random bytes
4 pg_dump to /backups (same mount) (never reached)
-- the dump file is plaintext: the volume key protects only the stolen diskReal scenarios: a decommissioned laptop with a local PostgreSQL; a cloud snapshot shared to the wrong account (it stays encrypted with a key the other account cannot use, if the key policy is right); a colocation server seized.
| Product | Volume-level option | Notes |
|---|---|---|
| PostgreSQL | LUKS, geli, BitLocker, cloud volume encryption | The manual's recommended route when you need encryption at rest and do not run pg_tde |
| MySQL, MongoDB, Oracle, SQL Server | The same, in addition to their own TDE | Independent layer, different key |
| RDS, Aurora, Cloud SQL, Azure SQL | One checkbox plus a KMS key | Amazon RDS: choose encryption when the instance is created; the docs list limitations for existing unencrypted instances |
| SQLite | Whole-file encryption through SQLCipher or the commercial SEE (third-party; not covered by the SQLite core) | File is one blob, so file-level encryption is natural |
| Redis | Volume encryption of the RDB/AOF files; open-source Redis has no built-in at-rest encryption | Managed services (ElastiCache and others) add a flag |
| CockroachDB | Store-level encryption at rest is documented as an enterprise feature (not fetched for this page: verify in its docs) | Plus volume encryption |
Fix / how to use it: turn it on for every production and backup volume, store the key in a KMS and not on the same host, and treat it as the baseline, never as the whole answer.
Transparent Data Encryption (TDE) Must-know
In plain words: the database engine itself encrypts its data files and log as it writes pages, and decrypts them as it reads, so applications and SQL do not change.
Common misunderstanding: “TDE hides data from the DBA.” It does not: a user who can run SELECT receives plaintext, because the engine decrypts pages into the buffer pool for every authorised query. TDE answers "somebody stole the files", not "somebody is allowed in".
Definition: engine-level encryption with a key hierarchy. Microsoft's description: "The encryption uses a database encryption key (DEK). The database boot record stores the key for availability during recovery. The DEK is a symmetric key, and is secured by a certificate that the server's master database stores" (or by an asymmetric key from an EKM module). MySQL: "InnoDB uses a two tier encryption key architecture, consisting of a master encryption key and tablespace keys."
MySQL InnoDB (8.4) SQL Server TDE
1 keyring component loaded at startup 1 CREATE MASTER KEY in master
2 master key = KEK, kept in keyring / KMIP / KMS 2 CREATE CERTIFICATE (protects the DEK)
3 CREATE TABLE t (...) ENCRYPTION='Y' 3 CREATE DATABASE ENCRYPTION KEY ... AES_256
4 tablespace key (DEK) created, wrapped by master 4 ALTER DATABASE shop SET ENCRYPTION ON
key, stored in the .ibd header 5 background scan encrypts every page
5 pages encrypted on write, decrypted on read 6 sys.dm_database_encryption_keys: state 3
6 ALTER INSTANCE ROTATE INNODB MASTER KEY -- tempdb is encrypted automatically
-- rewraps tablespace keys only: no data rewrite -- master/model/msdb cannot be encryptedReal scenarios: a PCI audit that asks for "encryption of stored account data" without changing the application; a hosted SQL Server where the provider cannot attach your database without your certificate; restoring a TDE-protected backup on a new server fails until you restore the certificate first.
| Engine | Feature name | Key hierarchy | Covers | Rotation | Gotchas (from the docs) |
|---|---|---|---|---|---|
| SQL Server, Azure SQL | TDE | Service master key → certificate in master or EKM → DEK (AES-128/192/256) | Data and log files, tempdb automatically, backups of the database | Re-encrypt with a new DEK; certificate rotation | Not available for master, model, msdb; replication does not replicate data encrypted; lose the certificate, lose the backups |
| Oracle | TDE | Keystore (wallet or HSM) master key → table or tablespace key | Column or whole tablespace; backups | ADMINISTER KEY MANAGEMENT re-key | Needs ADMINISTER KEY MANAGEMENT privilege; data outside the tablespace, such as BFILE, is not encrypted; docs: "The actual performance impact on applications can vary." |
| MySQL 8.4 InnoDB | Data-at-rest encryption | Keyring component master key → per-tablespace key | File-per-table, general, mysql system tablespace; redo and undo logs (innodb_redo_log_encrypt, innodb_undo_log_encrypt) | ALTER INSTANCE ROTATE INNODB MASTER KEY (supports concurrent DML) | Redo log encryption off by default; component_keyring_file keeps keys in a local file; Enterprise adds encrypted file, KMIP, AWS and others |
| MongoDB Enterprise | Encrypted Storage Engine | Master key in a KMIP server or keyfile → per-database keys | WiredTiger data files, journal | Rotate the master key (KMIP) | Enterprise only, WiredTiger only; default AES256-CBC, AES256-GCM supported on Linux |
| PostgreSQL | None in core | None | None | None | Use volume encryption, or Percona pg_tde (tde_heap access method for Percona Server for PostgreSQL 17 and 18: encrypts tuples, WAL and indexes, not yet temp files and statistics) |
| SQLite, Redis | None built in | None | None | None | SQLCipher/SEE for SQLite; volume encryption for Redis |
Fix / how to use it: the SQL for SQL Server, MySQL and Oracle is below; the page's Go and Laravel code does not apply because TDE is invisible to clients.
-- SQL Server: Transparent Data Encryption (run in master, then the user database).
USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<strong password>';
CREATE CERTIFICATE MyServerCert WITH SUBJECT = 'TDE DEK protector';
USE shop;
CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_256 ENCRYPTION BY SERVER CERTIFICATE MyServerCert;
ALTER DATABASE shop SET ENCRYPTION ON;
-- Progress and state: encryption_state 3 means encrypted.
SELECT db_name(database_id) AS db, encryption_state, percent_complete FROM sys.dm_database_encryption_keys;
-- MySQL 8.4 / InnoDB: data-at-rest encryption needs a keyring component loaded at startup.
CREATE TABLE card (id BIGINT PRIMARY KEY, pan_token VARCHAR(40)) ENCRYPTION = 'Y';
ALTER TABLE card ENCRYPTION = 'N'; -- rewrites the table
ALTER INSTANCE ROTATE INNODB MASTER KEY; -- re-wraps tablespace keys only
SELECT SPACE, NAME, ENCRYPTION FROM INFORMATION_SCHEMA.INNODB_TABLESPACES WHERE ENCRYPTION = 'Y';
-- my.cnf: innodb_redo_log_encrypt = ON, innodb_undo_log_encrypt = ON, binlog_encryption = ON
-- Oracle: tablespace encryption (wallet/keystore must be open).
ADMINISTER KEY MANAGEMENT SET KEY IDENTIFIED BY "<keystore password>" WITH BACKUP;
CREATE TABLESPACE secure_ts DATAFILE 'secure01.dbf' SIZE 100M ENCRYPTION USING 'AES256' DEFAULT STORAGE (ENCRYPT);PostgreSQL without TDE: the four alternatives Important
In plain words: vanilla PostgreSQL cannot encrypt its own files, so you either encrypt underneath it, around it, or inside the columns.
Common misunderstanding: “pgcrypto is PostgreSQL's TDE.” It is a toolbox of functions you call yourself, on chosen columns, with a key you supply per call; the key and plaintext pass through the server.
| Option | What it protects | Cost | Limit |
|---|---|---|---|
| Volume or file-system encryption (LUKS, cloud volume) | Whole cluster: heap, indexes, WAL, temp files, logs | Almost nothing; hardware AES | Mounted means readable |
pg_tde (Percona Server for PostgreSQL 17/18) | Tuples, WAL, indexes; keys from keyringfile or an external KMS through a global key provider | Vendor distribution, not stock PostgreSQL | Temp files and statistics not yet encrypted (README) |
pgcrypto columns | Chosen columns | Query changes; key handling in SQL | "All pgcrypto functions run inside the database server" |
| Application-side envelope encryption | Chosen fields, key never reaches the server | Search and constraints change | You own the crypto code |
| Managed service (RDS, Cloud SQL, Azure) | Volume, snapshot, backup | Provider lock-in on key | Provider-managed keys are still the provider's |
Fix / how to use it: most teams run volume encryption for the cluster plus application-side encryption for the few really sensitive fields.
WAL, temporary files, logs and swap: the places data leaks from Important
In plain words: the data file is not the only place your secrets appear. Every copy needs the same protection.
Common misunderstanding: “We encrypted the table, so the secret exists only in the table.” The plaintext also passes through the write-ahead log (WAL), sort and hash spill files, the query log, pg_stat_statements text, replication slots, core dumps and swap.
| Place | Why it holds data | Covered by |
|---|---|---|
| WAL / redo / binlog | Every change is logged before the data file | Volume encryption; pg_tde WAL; MySQL innodb_redo_log_encrypt, binlog_encryption; SQL Server TDE log |
Temp files (sorts, hash joins, temp_tablespaces) | Spill to disk when work_mem is exceeded | Volume encryption; TDE tempdb; pg_tde does not cover them yet |
| Server and slow-query logs | Statements with literal values, and with pgcrypto, with the key | log_statement, log_min_duration_statement settings; parameter logging off |
| Swap and core dumps | Memory pages written to disk | Encrypted swap, vm.swappiness, disable core dumps for the database user |
| Replicas and snapshots | Full copies | Same encryption on every node |
| Error messages and APM traces | Values in constraint errors and bound parameters | Scrub at the logging layer |
Keys and key hierarchy
Envelope encryption: DEK and KEK Must-know
In plain words: encrypt the data with a small throw-away data key, then lock that data key with a bigger key kept somewhere safe. To change the big key, re-lock the small keys; the data is not touched.
Common misunderstanding: “Rotating the key means re-encrypting the whole database.” Only if you encrypted data directly with the master key. With envelope encryption, rotation of the KEK rewraps the DEKs, which are a few dozen bytes each.
Definition: a DEK (data-encryption key) encrypts the data; a KEK (key-encryption key, in AWS terms a KMS key, formerly CMK) encrypts DEKs. AWS KMS documents it exactly so: "Data keys are symmetric keys you can use to encrypt data ... When AWS KMS generates data keys, it returns a plaintext data key for immediate use (optional) and an encrypted copy of the data key that you can safely store with the data. When you are ready to decrypt the data, you first ask AWS KMS to decrypt the encrypted data key." The KEK itself never leaves the KMS or its HSM (hardware security module).
Application KMS (HSM) Database
1 GenerateDataKey(kek-tenant-42) ->
2 <- DEK (plaintext) + wrapped DEK
3 nonce = random 96 bits
4 ct = AES-256-GCM(DEK, nonce, plaintext, AAD = "customers/1001/ssn")
5 zero the DEK in memory
6 INSERT (wrapped DEK, nonce||ct||tag) ------------------------------> stored together
-- read: SELECT row; Decrypt(wrapped DEK) -> DEK; AES-GCM open; tag check; zero DEKReal scenarios: one DEK per tenant (cheap, and deleting the tenant's KEK shreds the tenant); one DEK per row (more KMS calls, finer blast radius); a DEK per table partition or per file (S3 and EBS style); caching unwrapped DEKs in memory for seconds to cut KMS calls and latency.
| Property | Data key per record | Data key per tenant / table | Single key for all data |
|---|---|---|---|
| KMS calls | One per write and read (cache to reduce) | One per cache miss | Almost none |
| Blast radius of a DEK leak | One record | One tenant or table | Everything |
| Nonce-limit margin (2^32 messages per key) | Never an issue | Check high-volume tables | Hit eventually |
| Crypto-shredding | Delete the record's key | Delete the tenant's KEK | Impossible without re-encrypting |
| Rotation cost | Rewrap all wrapped DEKs | Rewrap few DEKs | Re-encrypt all data |
Fix / how to use it: the Go sketch Seal, Open and Rewrap against a KMS interface, with AAD binding the ciphertext to its row.
// Envelope encryption with a KMS boundary: a per-record data key (DEK) encrypts
// the field with AES-256-GCM, and a key-encryption key (KEK) that never leaves
// the KMS wraps the DEK. The KMS here is an in-memory stub.
package main
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"sync"
)
// KMS is the narrow interface to AWS KMS, GCP KMS, Azure Key Vault or Vault transit.
type KMS interface {
// GenerateDataKey returns a fresh 32-byte DEK in plaintext and wrapped under keyID.
GenerateDataKey(ctx context.Context, keyID string) (plain, wrapped []byte, err error)
// Decrypt unwraps a DEK. It fails once the KEK is destroyed.
Decrypt(ctx context.Context, keyID string, wrapped []byte) ([]byte, error)
// Encrypt wraps an existing DEK under keyID (used by rewrap).
Encrypt(ctx context.Context, keyID string, plain []byte) ([]byte, error)
}
// stubKMS keeps KEKs in memory. A real KMS keeps them in an HSM.
type stubKMS struct {
mu sync.Mutex
keks map[string][]byte
}
func newStubKMS(keyIDs ...string) *stubKMS {
k := &stubKMS{keks: map[string][]byte{}}
for _, id := range keyIDs {
kek := make([]byte, 32)
if _, err := rand.Read(kek); err != nil {
panic(err)
}
k.keks[id] = kek
}
return k
}
func (k *stubKMS) kek(id string) (cipher.AEAD, error) {
k.mu.Lock()
defer k.mu.Unlock()
raw, ok := k.keks[id]
if !ok {
return nil, fmt.Errorf("kms: key %q does not exist or was destroyed", id)
}
return newAEAD(raw)
}
// DestroyKey models scheduled key deletion: crypto-shredding in one call.
func (k *stubKMS) DestroyKey(id string) {
k.mu.Lock()
defer k.mu.Unlock()
delete(k.keks, id)
}
func (k *stubKMS) GenerateDataKey(ctx context.Context, keyID string) ([]byte, []byte, error) {
dek := make([]byte, 32)
if _, err := rand.Read(dek); err != nil {
return nil, nil, err
}
wrapped, err := k.Encrypt(ctx, keyID, dek)
if err != nil {
return nil, nil, err
}
return dek, wrapped, nil
}
func (k *stubKMS) Encrypt(_ context.Context, keyID string, plain []byte) ([]byte, error) {
aead, err := k.kek(keyID)
if err != nil {
return nil, err
}
return aead.Seal(nil, nil, plain, []byte(keyID)), nil
}
func (k *stubKMS) Decrypt(_ context.Context, keyID string, wrapped []byte) ([]byte, error) {
aead, err := k.kek(keyID)
if err != nil {
return nil, err
}
return aead.Open(nil, nil, wrapped, []byte(keyID))
}
// newAEAD returns AES-GCM with a random 96-bit nonce prepended to the ciphertext
// (Go 1.24+). One key must not seal more than 2^32 messages with random nonces.
func newAEAD(key []byte) (cipher.AEAD, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCMWithRandomNonce(block)
}
// Envelope is what you store in the column: the wrapped DEK sits next to the data.
type Envelope struct {
KeyID string // which KEK wrapped the DEK, for example "tenant-42/v1"
WrappedDEK []byte
Ciphertext []byte // nonce || ciphertext || tag
}
// Seal encrypts plaintext under a fresh DEK. aad binds the ciphertext to its
// row and column, so copying it to another row makes Open fail.
func Seal(ctx context.Context, kms KMS, keyID string, plaintext, aad []byte) (Envelope, error) {
dek, wrapped, err := kms.GenerateDataKey(ctx, keyID)
if err != nil {
return Envelope{}, err
}
defer zero(dek)
aead, err := newAEAD(dek)
if err != nil {
return Envelope{}, err
}
return Envelope{KeyID: keyID, WrappedDEK: wrapped, Ciphertext: aead.Seal(nil, nil, plaintext, aad)}, nil
}
// Open unwraps the DEK through the KMS and decrypts.
func Open(ctx context.Context, kms KMS, env Envelope, aad []byte) ([]byte, error) {
dek, err := kms.Decrypt(ctx, env.KeyID, env.WrappedDEK)
if err != nil {
return nil, fmt.Errorf("unwrap data key: %w", err)
}
defer zero(dek)
aead, err := newAEAD(dek)
if err != nil {
return nil, err
}
return aead.Open(nil, nil, env.Ciphertext, aad)
}
// Rewrap moves an envelope to a new KEK version without touching the ciphertext.
func Rewrap(ctx context.Context, kms KMS, env Envelope, newKeyID string) (Envelope, error) {
dek, err := kms.Decrypt(ctx, env.KeyID, env.WrappedDEK)
if err != nil {
return Envelope{}, err
}
defer zero(dek)
wrapped, err := kms.Encrypt(ctx, newKeyID, dek)
if err != nil {
return Envelope{}, err
}
env.KeyID, env.WrappedDEK = newKeyID, wrapped
return env, nil
}
func zero(b []byte) {
for i := range b {
b[i] = 0
}
}
func main() {
ctx := context.Background()
kms := newStubKMS("tenant-42/v1", "tenant-42/v2")
aad := []byte("customers/1001/national_id")
env, err := Seal(ctx, kms, "tenant-42/v1", []byte("0012345678"), aad)
if err != nil {
panic(err)
}
plain, _ := Open(ctx, kms, env, aad)
fmt.Printf("round trip: %s\n", plain)
_, err = Open(ctx, kms, env, []byte("customers/2002/national_id"))
fmt.Println("moved to another row:", err != nil)
env, _ = Rewrap(ctx, kms, env, "tenant-42/v2")
plain, _ = Open(ctx, kms, env, aad)
fmt.Printf("after rewrap to %s: %s\n", env.KeyID, plain)
kms.DestroyKey("tenant-42/v2")
_, err = Open(ctx, kms, env, aad)
if err == nil {
panic(errors.New("data should be unrecoverable after the KEK is destroyed"))
}
fmt.Println("after crypto-shredding:", err)
}KMS, HSM, BYOK and Vault transit Important
In plain words: a KMS is a service that holds the master keys and does the unwrapping for you after checking who is asking. An HSM is the tamper-resistant hardware box underneath.
Common misunderstanding: “Our keys are in the cloud KMS, so the cloud provider cannot read our data.” With a provider-managed key, the provider's KMS can decrypt for any principal your IAM policy lets in. For stronger separation you bring your own key (BYOK), hold it outside (HYOK or external key store), or encrypt client-side.
| Service | What it offers | Notes |
|---|---|---|
| AWS KMS | KMS keys in HSMs, GenerateDataKey, Encrypt, Decrypt, key policies, grants, automatic rotation, CloudTrail audit | RDS, EBS, S3 and Aurora use it for volume and snapshot keys |
| Google Cloud KMS, Azure Key Vault / Managed HSM | Same model, different IAM | Azure Key Vault holds the SQL Server TDE protector and Always Encrypted column master keys |
| HashiCorp Vault transit engine | "Cryptography as a service": encrypt, decrypt, rewrap, sign, HMAC, random bytes, data key generation; Vault does not store the data | Key versions and rewrap; derivation and optional convergent encryption; also the idea behind vault transit for tokenization |
| KMIP servers (Thales, Oracle Key Vault, Fornetix) | Standard key lifecycle protocol | MongoDB Encrypted Storage Engine and MySQL Enterprise keyring_okv speak it |
| PKCS#11 HSM (CloudHSM, Thales Luna) | Raw hardware key operations | Backing store for the others |
Fix / how to use it: call the KMS only for data keys, never per field when avoidable, grant the application GenerateDataKey and Decrypt on one key and nothing else, and alert on Decrypt calls that come from unexpected principals.
Rotation, re-encryption and the cryptoperiod Must-know
In plain words: keys age. Rotation means starting to use a new key; re-encryption means moving old data to it. They are different jobs with different costs.
Common misunderstanding: “We rotated the key last night, so old data is under the new key.” Rotating a KMS key creates a new version for new operations; old ciphertext still needs the old version until you rewrap or re-encrypt it, which is why old key versions are kept, not deleted.
Definition: NIST SP 800-57 calls the period a key may be used its cryptoperiod. Rotation cost depends on what the key wraps: a root key or KEK rotation is a rewrap of DEKs (cheap), a DEK rotation re-encrypts that DEK's data (expensive for large tables).
Laravel APP_KEY rotation (Laravel 13 encrypter)
1 APP_KEY=base64:NEW... APP_PREVIOUS_KEYS=base64:OLD...
2 new writes: encrypted with the current key
3 reads: try the current key, then each previous key until one works
4 run crypto:reencrypt to rewrite stored ciphertext under the new key
5 verify no row still needs OLD, then remove it from APP_PREVIOUS_KEYS
-- remove OLD too early at step 5 and every untouched row throws DecryptException| Rotation scenario | What is rewritten | Downtime | Product feature |
|---|---|---|---|
| KEK / master key | Wrapped DEKs only | None | MySQL ALTER INSTANCE ROTATE INNODB MASTER KEY; Vault rewrap; AWS KMS key rotation keeps old versions |
| TDE DEK (database key) | Whole database re-encrypted in the background | Online, with I/O and CPU cost | SQL Server new DEK; Oracle re-key; ALTER TABLE ... ENCRYPTION in MySQL rewrites the table |
| Application field key | Every encrypted column of every row | Online if done in batches | Laravel APP_PREVIOUS_KEYS plus a re-encryption command; Tink keyset rotation |
| TLS certificate | Nothing stored | None if reloaded | pg_reload_conf() in PostgreSQL; ALTER INSTANCE RELOAD TLS in MySQL |
Key loss is data loss, and crypto-shredding is deletion Must-know
In plain words: if you lose every copy of a key, the data is gone for everyone, including you. That is also the trick behind deleting data from backups: destroy the key.
Common misunderstanding: “Backups are our safety net, so we can recreate anything.” An encrypted backup without its key (a SQL Server TDE certificate, an Oracle wallet, a KMS key scheduled for deletion, an APP_KEY nobody saved) is random bytes.
Definition: crypto-shredding (cryptographic erasure) deletes the key that wrapped a record or a tenant's data so that every copy, including in backups and replicas, becomes unreadable. It answers GDPR-style erasure requests in immutable storage where rewriting is impractical.
Tenant 42 asks for deletion Backups, replicas, logs
1 all tenant-42 DEKs are wrapped by KEK tenant-42/v3
2 schedule deletion of KEK tenant-42/v3 (cloud KMS: waiting period of days)
3 wait period ends, KEK destroyed
4 Decrypt(wrapped DEK) -> error every old copy is now noise
-- unwrapped DEKs cached in memory must be flushed too; never log keysReal scenarios: a startup loses the only copy of APP_KEY when the server is rebuilt and every encrypted column becomes unreadable; a SQL Server restore on a new host fails with "Cannot find server certificate with thumbprint ..." because the certificate was not backed up; an audit asks you to prove deletion of a user from year-old backups.
| Practice | Why |
|---|---|
| Back up keys separately from data, in at least two places, with access reviews | Key loss is unrecoverable |
| Use KMS key policies and a waiting period for deletion | A mistaken ScheduleKeyDeletion can be cancelled |
| Test restore of an encrypted backup on a clean machine regularly | Proves the key path, not just the data path |
| Document who may use and who may administer each key (separation of duties) | NIST key-management guidance |
Never put keys in the repository, .env files in images, or logs | See secrets management |
Encryption in transit
The baseline (what sslmode values mean, why require still allows a man-in-the-middle, the Laravel .env keys) is in Database Security: TLS with server verification. This section adds what that page does not: protocol versions, mutual TLS, replication links, poolers, MySQL's side and a Go client.
TLS versions, ciphers and certificates Important
In plain words: TLS gives you two things: a secret channel and proof that the other end is who it says. Old protocol versions weaken the first; skipping verification loses the second.
Common misunderstanding: “TLS is on, so the connection is authenticated.” Only when the client verifies the chain and the host name (verify-full).
Definition: PostgreSQL's ssl_min_protocol_version accepts TLSv1, TLSv1.1, TLSv1.2, TLSv1.3; the default is TLSv1.2, which "satisfies industry best practices as of this writing". Client side, libpq has ssl_min_protocol_version and ssl_max_protocol_version. hostssl lines in pg_hba.conf accept only TLS connections; hostnossl accepts only plaintext; host accepts both. Besides TLS, PostgreSQL supports GSSAPI encryption (hostgssenc, gssencmode=require), and "Stunnel or SSH can also be used to encrypt transmissions."
| Knob | Product | Meaning |
|---|---|---|
ssl = on, ssl_cert_file, ssl_key_file, ssl_ca_file | PostgreSQL | Server certificate, key, CA for client certificates |
ssl_min_protocol_version, ssl_ciphers, ssl_prefer_server_ciphers | PostgreSQL | Floor for TLS version; cipher list for TLS 1.2 |
hostssl, hostnossl, hostgssenc | pg_hba.conf | Which connection types a line matches |
require_secure_transport = ON | MySQL | Reject non-TLS connections (error 3159) |
tls_version, ssl_ca, ssl_cert, ssl_key | MySQL | Allowed protocols and certificate files |
net.tls.mode, net.tls.CAFile | MongoDB mongod | requireTLS and certificate files |
tls-port, tls-cert-file, tls-auth-clients | Redis | TLS listener, certificate, client-certificate policy |
Encrypt=True; TrustServerCertificate=False | SQL Server clients | Encrypt and verify; the default of drivers has changed across versions, so set it explicitly |
Mutual TLS (mTLS) for databases Important
In plain words: both sides show a certificate. The database knows which client is calling without a password.
Common misunderstanding: “mTLS replaces authorization.” It authenticates the client machine or service; roles and privileges still decide what it may do.
Definition: in PostgreSQL, set ssl_ca_file and add clientcert=verify-ca or clientcert=verify-full to hostssl lines; verify-full also checks that the client certificate's common name matches the database user name (or a pg_ident map). auth-method cert makes the certificate the whole authentication. MySQL uses account REQUIRE X509 | SUBJECT | ISSUER. MongoDB uses x.509 authentication.
psql with a client certificate Server
1 ClientHello ->
2 <- ServerHello, server certificate, CertificateRequest
3 verify server chain + name (sslmode=verify-full)
4 client certificate (CN = shop_app) -> verify against ssl_ca_file
5 <- pg_hba: hostssl ... clientcert=verify-full
6 session as role shop_app, no password sent
-- steps 4 and 5 fail with "tlsv13 alert certificate required" or "unknown ca" when the client has no valid certificateReplication, backups and poolers: the hops people forget Must-know
In plain words: your application uses TLS, but the links between database nodes, the pooler and the backup tool are separate connections with their own settings.
Common misunderstanding: “Internal network traffic does not need TLS.” Lateral movement and mirrored ports exist; compliance frameworks also expect protection of data in transit inside the network for cardholder or health data.
| Hop | How to encrypt it | Detail |
|---|---|---|
| Streaming replication standby → primary | primary_conninfo is a libpq connection string: put sslmode=verify-full sslrootcert=... sslcert=... sslkey=... in it; the primary needs a hostssl replication line | Same for CREATE SUBSCRIPTION ... CONNECTION in logical replication |
| MySQL replication | SOURCE_SSL=1, SOURCE_SSL_CA, SOURCE_SSL_VERIFY_SERVER_CERT=1 in CHANGE REPLICATION SOURCE TO | Check with SHOW REPLICA STATUS |
| MongoDB replica set | net.tls.mode: requireTLS plus cluster x.509 (clusterAuthMode) | Members authenticate each other |
| PgBouncer client → pooler | client_tls_sslmode, client_tls_key_file, client_tls_cert_file, client_tls_ca_file | Default disable |
| PgBouncer pooler → PostgreSQL | server_tls_sslmode (default prefer; use verify-full), server_tls_ca_file | Two separate TLS sessions; see Connection Pooling |
Backup tools (pg_basebackup, pgBackRest, mysqldump) | Same sslmode settings in the connection string; repository encryption in the tool | Backup stream and backup repository are separate concerns |
| Cross-region and WAN replication | TLS plus a private link or VPN; certificates with the replica's real DNS name | verify-full fails if you connect by IP and the SAN lacks it |
The full lab for this lives at the end of the page: the same server, reached by a name inside the certificate and by its IP, shows exactly what verify-full adds.
// A tls.Config that behaves like libpq sslmode=verify-full, plus an optional
// client certificate for mutual TLS (pg_hba.conf clientcert=verify-full).
package main
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
)
// NewTLSConfig verifies the server chain against caFile and the host name
// against serverName. InsecureSkipVerify stays false: that is what makes it
// verify-full and not "require".
func NewTLSConfig(caFile, serverName, certFile, keyFile string) (*tls.Config, error) {
pem, err := os.ReadFile(caFile)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pem) {
return nil, errors.New("no certificate found in " + caFile)
}
cfg := &tls.Config{
RootCAs: pool,
ServerName: serverName, // matched against the certificate SAN
MinVersion: tls.VersionTLS12,
}
if certFile != "" {
pair, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{pair}
}
return cfg, nil
}
func main() {
ca, host := os.Getenv("DB_CA"), os.Getenv("DB_HOST")
if ca == "" || host == "" {
fmt.Println("set DB_CA=/path/ca.pem and DB_HOST=db-lab to dial (optional DB_PORT)")
return
}
port := os.Getenv("DB_PORT")
if port == "" {
port = "5432"
}
cfg, err := NewTLSConfig(ca, host, os.Getenv("DB_CERT"), os.Getenv("DB_KEY"))
if err != nil {
fmt.Println("config:", err)
os.Exit(1)
}
// PostgreSQL negotiates TLS after an SSLRequest packet, so a raw tls.Dial only
// works against a TLS-first endpoint (a proxy or a direct-TLS listener).
conn, err := tls.Dial("tcp", host+":"+port, cfg)
if err != nil {
fmt.Println("handshake failed:", err)
os.Exit(1)
}
defer conn.Close()
st := conn.ConnectionState()
fmt.Printf("TLS %s cipher %s\n", tls.VersionName(st.Version), tls.CipherSuiteName(st.CipherSuite))
}Column and application-level encryption
Deterministic vs randomised encryption Must-know
In plain words: randomised encryption gives a different ciphertext every time you encrypt the same value, so nobody learns anything from the ciphertexts. Deterministic encryption gives the same ciphertext for the same value, so the database can match them, and so can an attacker who counts.
Common misunderstanding: “Deterministic encryption is just as safe, and it lets me query.” It leaks equality and frequency. MongoDB's own page says it: deterministic encryption "provides greater support for read operations", but "encrypted data with low cardinality is susceptible to frequency analysis recovery". A column holding true/false or ten country codes is readable by counting.
Definition: a randomised scheme uses a fresh nonce or IV per encryption (AES-GCM with a random 96-bit nonce, pgp_sym_encrypt, Laravel's encrypted). A deterministic scheme derives the nonce from the key and plaintext (AES-SIV, Vault transit convergent mode, SQL Server DETERMINISTIC, MongoDB AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic). SQL Server's docs: "Randomized encryption uses a method that encrypts data unpredictably. Each identical plaintext input results in a distinct encrypted output."
value randomised (AES-GCM, random nonce) deterministic (AES-SIV)
1 "Iran" 9f3a... (run 1) c41e...
2 "Iran" 07be... (run 2) different every time c41e... same every time
3 "Iran" b21c... (run 3) c41e...
4 GROUP BY country on ciphertext: useless GROUP BY works; 40% of rows share c41e... -> "Iran" is the most common value
-- an attacker with the column and public statistics (population shares) maps ciphertexts to countries| Property | Randomised | Deterministic |
|---|---|---|
Equality WHERE col = ? | No | Yes |
GROUP BY, DISTINCT, equality joins | No | Yes |
| Unique constraint | No | Yes |
| Frequency analysis | Immune | Vulnerable on low-cardinality data |
Range, ORDER BY, LIKE | No | No |
| Best for | Card numbers, notes, health data, high-cardinality secrets | Identifiers that must be looked up: email, national ID, with care |
Fix / how to use it: default to randomised. When you must look values up, prefer a randomised ciphertext plus a blind index (next section), because you can truncate or key the index separately and drop it later.
Searchable encryption with a blind index Must-know
In plain words: store the encrypted value for reading and, next to it, a keyed fingerprint of the value for searching. To search, fingerprint the search term and compare fingerprints.
Common misunderstanding: “A SHA-256 of the email is a blind index.” An unkeyed hash of a guessable value (emails, phone numbers, national IDs) can be reversed by hashing a dictionary. A blind index must be an HMAC with a secret key that is not the encryption key.
Definition: bidx = HMAC-SHA256(blind_key, field_name || 0x00 || normalise(value)), optionally truncated. Normalisation (lowercase, trim, Unicode normal form, phone digits only) must match on write and search. Equality, IN lists and uniqueness work; range, prefix, LIKE and sorting do not. The cost is leakage of equality among rows, which is the same as deterministic encryption, but only of the index column and under a separate key.
INSERT customer (email = "Ann@Example.com") SELECT ... WHERE email = " ann@example.com "
1 normalise -> "ann@example.com" normalise -> "ann@example.com"
2 bidx = HMAC(blind_key, "email" || 0 || normalised) bidx = HMAC(blind_key, "email" || 0 || normalised)
3 email_enc = AES-GCM(data_key, random nonce, "Ann@...") WHERE email_bidx = :bidx (B-tree, fast)
4 store (email_enc, email_bidx) decrypt each hit, compare, drop false positives
-- truncating bidx to 8 bytes makes unrelated emails collide on purpose: hides which exact rows are equalReal scenarios: login by email when emails are encrypted; "has this national ID already registered" uniqueness check; GDPR lookup of all rows of a person; matching payments by encrypted card fingerprint.
| Design choice | Effect |
|---|---|
Separate blind_key per field | Equal values in two columns do not match across columns |
| Include the field name in the HMAC input | Same, even with one key |
| Truncate the index (8 to 16 bytes) | Fewer distinct values, some false positives, less leakage |
| Add a pepper from a KMS | Cracking needs the KMS |
| Several indexes (full, last 4 digits) | Prefix-like search at the price of leaking the short values |
| Rotation | Recompute every index when the blind key changes: plan for it |
Fix / how to use it: SQL with pgcrypto, Go and Laravel versions follow in the next blocks and in the lab.
// Blind index: a keyed HMAC of the normalised value, stored next to the
// randomised ciphertext, so equality search works without deterministic encryption.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
)
// BlindIndex returns the first `bytes` bytes of HMAC-SHA256(key, field || 0x00 || normalised).
// The field name is mixed in so equal values in different columns get different indexes.
// Truncating (for example to 8 bytes) makes the index collide on purpose: several
// different values share one index value, which leaks less, and the application
// filters the false positives after decrypting.
func BlindIndex(key []byte, field, value string, bytes int) string {
mac := hmac.New(sha256.New, key)
mac.Write([]byte(field))
mac.Write([]byte{0})
mac.Write([]byte(normalize(value)))
sum := mac.Sum(nil)
if bytes > 0 && bytes < len(sum) {
sum = sum[:bytes]
}
return hex.EncodeToString(sum)
}
// normalize must be identical on the write path and the search path.
func normalize(v string) string {
return strings.ToLower(strings.TrimSpace(v))
}
func main() {
key := []byte("0123456789abcdef0123456789abcdef") // demo only: load from a KMS in real code
a := BlindIndex(key, "email", "Alice@Example.com ", 16)
b := BlindIndex(key, "email", "alice@example.com", 16)
c := BlindIndex(key, "backup_email", "alice@example.com", 16)
fmt.Println("same value, different case/spaces:", a == b)
fmt.Println("same value, different column: ", a == c)
fmt.Println("index:", a)
// SELECT id, email_enc FROM customers WHERE email_bidx = $1
// then decrypt email_enc and compare with the searched value.
}pgcrypto: encryption inside PostgreSQL Important
In plain words: pgcrypto gives SQL functions to hash, encrypt and decrypt. The key travels in the query, so the server sees it.
Common misunderstanding: “pgp_sym_encrypt(data, key) keeps the key away from the DBA.” The manual is blunt: "All pgcrypto functions run inside the database server. That means that all the data and passwords move between pgcrypto and client applications in clear text. Thus you must: Connect locally or use SSL connections. Trust both system and database administrator. If you cannot, then better do crypto inside client application." It also warns that the implementation "does not resist side-channel attacks".
Definition: pgcrypto is a trusted extension (installable by a non-superuser with CREATE on the database) and needs OpenSSL. Families: digest(), hmac(), crypt() with gen_salt() (password hashing: bf, md5, xdes, des), pgp_sym_encrypt, pgp_sym_decrypt, pgp_pub_encrypt, pgp_pub_decrypt, armor()/dearmor(), raw encrypt()/decrypt() (discouraged: no integrity check, user key used directly, you manage the IV), gen_random_bytes() and gen_random_uuid(). PGP options include cipher-algo=aes256, compress-algo, s2k-mode, s2k-count.
psql session What leaks on the server
1 \set dek `cat /run/secrets/dek`
2 INSERT ... pgp_sym_encrypt(:'ssn', :'dek') statement text reaches the server; with log_statement = 'all' it reaches the log
3 pg_stat_statements stores the normalised text constants are replaced, but pg_stat_activity shows the running query text
4 SELECT pgp_sym_decrypt(ssn_enc, :'dek') ... plaintext result sent over the connection: TLS needed
-- a superuser can read the key from memory, the log or the running query| Function | Use | Caution |
|---|---|---|
pgp_sym_encrypt(text, key, 'cipher-algo=aes256') | Randomised, integrity-protected, salted | Key in the query; slow s2k is deliberate |
pgp_pub_encrypt(text, pubkey) | Write-only column: anyone can encrypt, only the private key holder can read | Private key must be supplied to decrypt |
hmac(data, key, 'sha256') | Blind index | Same: key sits in the SQL |
crypt(password, gen_salt('bf', 12)) | Password hash | Prefer hashing in the application with argon2id |
encrypt(), decrypt() raw | Legacy | The manual discourages them |
-- pgcrypto column encryption plus a blind index, PostgreSQL 14+.
-- Keys come from psql variables so they are not in the file:
-- psql -v dek="$DEK" -v bidx="$BIDX" -f pgcrypto-column.sql
-- Remember: the statement text (with the key) reaches the server, and may reach
-- the server log with log_statement = 'all' or log_min_duration_statement.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE customer (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
email_enc bytea NOT NULL, -- OpenPGP symmetric message, random salt and IV each time
email_bidx bytea NOT NULL -- HMAC-SHA256, searchable for equality
);
CREATE INDEX customer_email_bidx ON customer (email_bidx);
INSERT INTO customer (name, email_enc, email_bidx)
SELECT 'Ann',
pgp_sym_encrypt(e, :'dek', 'cipher-algo=aes256'),
hmac(lower(trim(e)), :'bidx', 'sha256')
FROM (VALUES ('Ann@Example.com')) AS v(e);
-- Same plaintext inserted twice gives two different ciphertexts (randomised) ...
INSERT INTO customer (name, email_enc, email_bidx)
SELECT 'Ann (copy)',
pgp_sym_encrypt(e, :'dek', 'cipher-algo=aes256'),
hmac(lower(trim(e)), :'bidx', 'sha256')
FROM (VALUES ('Ann@Example.com')) AS v(e);
SELECT count(DISTINCT email_enc) AS distinct_ciphertexts,
count(DISTINCT email_bidx) AS distinct_blind_indexes
FROM customer; -- 2 and 1
-- ... yet equality search works through the blind index.
SELECT id, name, pgp_sym_decrypt(email_enc, :'dek') AS email
FROM customer
WHERE email_bidx = hmac(lower(trim(' ann@example.com ')), :'bidx', 'sha256');
-- Range and LIKE do not work: the ciphertext carries no order.
-- SELECT ... WHERE pgp_sym_decrypt(email_enc, :'dek') LIKE 'ann%' -- full scan, decrypts every rowTokenization and format-preserving encryption Important
In plain words: instead of storing the card number, store a random stand-in (token) and keep the real number in a tiny, heavily guarded vault. Format-preserving encryption gives a ciphertext that looks like the original (16 digits stay 16 digits).
Common misunderstanding: “A token is an encrypted value.” A random token has no mathematical relation to the original; only the vault mapping connects them, which is why tokens can shrink PCI scope: systems that see only tokens never touch card data.
| Technique | How it works | Reversible by | Keeps format | Typical use |
|---|---|---|---|---|
| Vault tokenization | Random token; mapping stored in a secured vault (or Vault transit tokenization) | Vault lookup | Yes (you choose) | PCI card numbers, national IDs |
| Format-preserving encryption (FF1, FF3-1 in NIST SP 800-38G) | Block-cipher construction over a digit or alphabet domain | Key holder | Yes | Legacy columns with fixed formats, test data |
| Deterministic tokens (HMAC-based) | Token derived from value and key | Nobody (one-way) | Optional | Joins across systems without sharing values |
| Randomised encryption | Standard AEAD | Key holder | No | General fields |
FPE has small domains by nature (10 digits has only 10^10 values), so deterministic FPE is highly exposed to frequency and dictionary attacks; use tweaks (a per-record value such as the account ID) and treat it as a compatibility tool, not a first choice.
Application-level encryption in Laravel Must-know
In plain words: declare a column encrypted in the model's casts; Laravel encrypts on save and decrypts on read.
Common misunderstanding: “Laravel can search encrypted columns.” The docs: "since the values are encrypted in the database, you will not be able to query or search encrypted attribute values." Add a blind index column and a scope.
Definition: Laravel's encrypter "provide[s] a simple, convenient interface for encrypting and decrypting text via OpenSSL using AES-256 and AES-128 encryption", and every value is signed with a MAC. The encrypted cast, plus encrypted:array, encrypted:collection, encrypted:object, AsEncryptedArrayObject and AsEncryptedCollection, store ciphertext, which is longer and variable, so the column must be TEXT or larger. Crypt::encryptString() / Crypt::decryptString() do the same by hand, and a failed MAC raises DecryptException. The key is APP_KEY; for rotation, list old keys in APP_PREVIOUS_KEYS: Laravel "will always use the 'current' encryption key when encrypting values", and when decrypting it tries the current key and then "all previous keys until one of the keys is able to decrypt the value."
| Piece | Where | Note |
|---|---|---|
casts() with 'email' => 'encrypted' | Model | Same key for every row: tenant keys need a custom cast |
email_bidx column and saving hook | Migration, model | HMAC with its own key from config('services.blind_index.key') |
whereEmailIs() scope | Model | Normalises, computes HMAC, filters on the index |
crypto:reencrypt command | Artisan | Raw DB::table update because Eloquent skips unchanged plaintext |
APP_PREVIOUS_KEYS | .env | Remove an old key only after re-encryption is verified |
<?php
namespace App\Models;
use App\Support\BlindIndex;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['name', 'email', 'national_id'];
/**
* The encrypted cast stores AES-256 ciphertext made with APP_KEY. It cannot
* be queried: every encryption uses a fresh IV, so two equal values differ.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email' => 'encrypted',
'national_id' => 'encrypted',
];
}
protected static function booted(): void
{
// Keep the blind index in step with the plaintext on every save.
static::saving(function (Customer $customer): void {
if ($customer->isDirty('email') || ! $customer->exists) {
$customer->email_bidx = BlindIndex::for('email', (string) $customer->email);
}
});
}
/**
* Equality search over an encrypted column through the blind index.
*
* @param Builder<Customer> $query
* @return Builder<Customer>
*/
public function scopeWhereEmailIs(Builder $query, string $email): Builder
{
return $query->where('email_bidx', BlindIndex::for('email', $email));
}
}<?php
namespace App\Support;
use RuntimeException;
/**
* Keyed HMAC of a normalised value, used as a searchable "blind index".
* Use a key that is different from APP_KEY, so rotating one does not break the other.
*/
final class BlindIndex
{
public static function for(string $field, string $value, int $bytes = 16): string
{
$key = base64_decode((string) config('services.blind_index.key'), true);
if ($key === false || strlen($key) < 32) {
throw new RuntimeException('services.blind_index.key must be base64 of at least 32 bytes.');
}
$normalised = mb_strtolower(trim($value));
$raw = hash_hmac('sha256', $field."\0".$normalised, $key, true);
// Truncation makes different values collide on purpose; filter after decrypting.
return bin2hex(substr($raw, 0, $bytes));
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('customers', function (Blueprint $table): void {
$table->id();
$table->string('name');
// Ciphertext is longer than the plaintext and its length varies: use TEXT.
$table->text('email');
$table->text('national_id')->nullable();
// Blind index: hex of a truncated HMAC, indexed for equality search only.
$table->string('email_bidx', 32)->index();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('customers');
}
};Client-side field-level encryption
MongoDB CSFLE and Queryable Encryption Must-know
In plain words: the MongoDB driver encrypts chosen fields before they leave your application. The server stores and indexes ciphertext and never holds the key.
Common misunderstanding: “CSFLE and Queryable Encryption are the same thing.” CSFLE offers deterministic (equality-queryable) or randomised (not queryable) algorithms; Queryable Encryption is a newer scheme, described as a "fast, searchable encryption scheme", that supports equality, range, prefix, suffix and substring queries while keeping payloads randomised, at the price of extra encrypted metadata and larger payloads (our inference from the design; check the limits page for your driver).
Definition: CSFLE "enables you to encrypt data in your application before you send it over the network to MongoDB. With CSFLE enabled, no MongoDB product has access to your data in an unencrypted form." Both support automatic encryption (you declare which fields are encrypted, and the driver encrypts and decrypts without explicit calls) and explicit encryption (you call the driver's encryption library and write the logic yourself). Keys are DEKs stored in a key vault collection, wrapped by a customer master key in AWS KMS, Azure Key Vault, GCP KMS, KMIP or a local key (local is for development only).
| Aspect | CSFLE | Queryable Encryption |
|---|---|---|
| Algorithms | Deterministic or randomised AEAD | Randomised with encrypted indexes |
| Query types | Equality (deterministic only) | Equality, range, prefix, suffix, substring |
| Leakage | Equality and frequency for deterministic fields | Designed to hide frequency; documented leakage profile |
| Cost | Low | Extra metadata, larger payloads, more driver work |
| Server sees | Ciphertext | Ciphertext and encrypted index data |
SQL Server Always Encrypted and secure enclaves Must-know
In plain words: the client driver encrypts and decrypts the column; the SQL Server engine never sees plaintext or keys, and the driver rewrites queries so your SQL stays almost unchanged.
Common misunderstanding: “With Always Encrypted I can use any T-SQL on the column.” Without enclaves the docs list the limits: no sorting or filtering "(except for point-lookups using deterministic encryption)", and randomised encryption "doesn't support searching, grouping, indexing, or joining."
Definition: two key types: column encryption keys (CEK, encrypt the data) and column master keys (CMK, "a key-protecting key that encrypts one or more column encryption keys"), the CMK stored "in a trusted key store outside of the database system, such as Azure Key Vault, Windows certificate store, or a hardware security module." Always Encrypted with secure enclaves (SQL Server 2019 and later, Azure SQL Database) "enables the database engine to process encrypted data within a protected memory area called a secure enclave", which brings pattern matching, comparison operators, sorting, indexing on randomised columns and in-place encryption, at the price of trusting the enclave and its attestation.
| Mode | Equality | Range, LIKE, sort | Joins and GROUP BY | Trust assumption |
|---|---|---|---|---|
| Deterministic | Yes | No | Yes | Server never sees plaintext |
| Randomised | No | No | No | Server never sees plaintext |
| Randomised + secure enclave | Yes | Yes | Yes | Enclave (VBS enclaves; the Azure SGX variant is being retired) and attestation service |
What the client-side designs have in common Good to know
In plain words: all three (Laravel casts, CSFLE, Always Encrypted) move the key out of the database, so the DBA, the backup and the cloud operator see only ciphertext; and all three pay by losing server-side query power.
Common misunderstanding: “If the field is encrypted client-side, my analytics team can still query it.” Aggregations, reports and ad-hoc SQL on that column stop working; plan a separate pseudonymised column or a derived metric for analytics.
| Concern | Consequence |
|---|---|
| Indexes | Only on blind indexes or deterministic ciphertext |
| Constraints | UNIQUE on the index column; CHECK cannot see plaintext |
| Migrations | Changing the type or format means decrypt, transform, encrypt in the application |
| Backups and replicas | Safe without extra work, until you restore without the key |
| Reporting | Needs decryption in application or a controlled decrypt service |
Encryption in use
Confidential computing: SEV-SNP, TDX, SGX Important
In plain words: the CPU encrypts a virtual machine's or program's memory with a key the host cannot read, so even the cloud operator's hypervisor sees only noise. The data is decrypted only inside the CPU.
Common misunderstanding: “Confidential computing makes my database unhackable.” It protects against the host, hypervisor and some physical memory attacks. It does not protect against bugs in your own database, a malicious SQL user, or the application that is allowed to read the data, and research has published side-channel attacks on hardware enclaves (this is outside the sources read for this page; treat the technology as risk reduction).
Definition: Google Cloud's Confidential VM description: hardware-based memory encryption "to help ensure that your data and applications can't be read or modified while in use", with isolation ("Encryption keys are generated by—and reside solely in—dedicated hardware, inaccessible to the hypervisor") and attestation ("You can verify the identity and the state of the VM"). The hardware options: AMD SEV-SNP (Secure Encrypted Virtualization with Secure Nested Paging, "adding hardware-based security to help prevent malicious hypervisor-based attacks like data replay and memory remapping"), Intel TDX (Trust Domain Extensions: an isolated "trust domain (TD) within a VM"), and Intel SGX, which "helps protect data in use via application isolation technology", with "hardened enclaves" for selected code and data.
Relying party (your app / KMS) Confidential VM running PostgreSQL
1 start VM with SEV-SNP or TDX enabled
2 <- attestation report signed by the CPU vendor key
3 verify signature, measurement (boot image hash), policy
4 release the data key / DB password only if the measurement matches
5 -> database starts, decrypts data inside the protected VM
-- the host sees ciphertext in RAM; if the measurement differs (tampered image) step 4 never happens| Technology | Protects | Granularity | Notes |
|---|---|---|---|
| AMD SEV, SEV-SNP | Whole VM memory; SNP adds integrity against replay and remapping | VM | Lift-and-shift: run PostgreSQL unchanged in a Confidential VM |
| Intel TDX | Trust domain (VM) memory | VM | Similar model on Intel; attestation from the platform |
| Intel SGX | Selected code and data in an enclave | Process or enclave | Requires application changes; small protected memory. SQL Server docs: Always Encrypted enclaves on SQL Server 2019 and later use VBS enclaves ("Intel SGX enclaves aren't supported"), and the SGX variant in Azure SQL Database reaches end of support on October 31, 2027 |
| Azure / GCP / AWS confidential offerings | The above as a VM type or Nitro Enclaves | VM or enclave | Check region and machine type support |
Real scenarios: a bank running its card database in a public cloud under a regulator that forbids provider access; a multi-party analytics where each party releases keys only to an attested enclave; healthcare data processed in Confidential VMs with keys held in an external KMS that checks attestation.
Homomorphic encryption: PHE, SHE, FHE Good to know
In plain words: you can add or multiply numbers while they stay encrypted; only the key holder can read the result. The server computes without ever seeing the data.
Common misunderstanding: “Homomorphic encryption lets the database run any SQL on encrypted data.” The Microsoft SEAL README: "Homomorphic encryption is not a generic technology: only some computations on encrypted data are possible. It also comes with a substantial performance overhead", and encrypted data is "many times larger than unencrypted data, so it may not make sense to encrypt, e.g., entire large databases". Useful cases are "scenarios where strict privacy requirements prohibit unencrypted cloud computation altogether, but the computations themselves are fairly lightweight."
Definition: schemes are grouped by what they can compute.
| Class | Operations | Examples | Practical use |
|---|---|---|---|
| PHE (partially homomorphic) | One operation, unlimited times: addition (Paillier) or multiplication (RSA textbook, ElGamal) | Paillier sum of encrypted salaries | Encrypted SUM, voting tallies, ad measurement |
| SHE / levelled HE (somewhat) | Both addition and multiplication, but limited circuit depth before noise grows too large | BFV, BGV, CKKS (approximate numbers) | Small statistics, linear models, private set operations |
| FHE (fully) | Arbitrary computation, using bootstrapping to refresh noise | TFHE, BGV and CKKS with bootstrapping (HElib implements BGV with bootstrapping and CKKS) | Research, specialised private inference; very slow for general queries |
Libraries: Microsoft SEAL (C++, MIT licence) and HElib (open source, Apache 2.0) implement the lattice-based schemes; Paillier is available in many language libraries. Realistically: encrypted sums and counts in a small result set are practical; joins, sorts and arbitrary SQL over big tables are not, which is why enclaves (hardware) are the practical answer to "compute on encrypted data" in production databases, and why this page's recommended order is: TDE and TLS first, application encryption for secrets, enclaves or confidential VMs when the host is the adversary, homomorphic only for narrow, lightweight computations. No vendor page read for this chapter published slowdown figures; measure on your own workload, and treat any single published multiplier with suspicion because it depends on scheme, parameters and hardware.
Encrypted salary total with Paillier (PHE)
1 client: c1 = Enc(pk, 4200) c2 = Enc(pk, 5100) -> sends c1, c2
2 server: c_sum = c1 * c2 mod n^2 (multiplying ciphertexts adds plaintexts)
3 server: returns c_sum -> never saw 4200 or 5100
4 client: Dec(sk, c_sum) = 9300
-- one SUM over a few thousand rows is fine; ORDER BY, joins and LIKE over millions of rows are notHashing, passwords and masking
Passwords are hashed, never encrypted Must-know
In plain words: nobody, including you, should be able to turn a stored password back into the password. So store a slow one-way hash with a unique salt.
Common misunderstanding: “Encrypting passwords with AES-256 is the strongest option.” If the key leaks, every password leaks. OWASP: passwords "must be protected using strong, slow hashing algorithms such as Argon2id, bcrypt, or PBKDF2", with a "unique salt", and "Fast hashing algorithms such as SHA-256 are not suitable for password storage".
Definition: use Argon2id (OWASP minimum: 19 MiB memory, 2 iterations, parallelism 1), or bcrypt when Argon2id is unavailable. Laravel's Hash facade defaults to bcrypt and supports argon2id through config (HASH_DRIVER=argon2id); the hashed cast hashes on assignment. Go: golang.org/x/crypto/argon2 (argon2.IDKey) and bcrypt. PostgreSQL stores role passwords as SCRAM hashes (password_encryption), and its manual says MD5 support "is deprecated and will be removed in a future release". See Database Security: authentication.
| Need | Right tool | Wrong tool |
|---|---|---|
| Store a user password | argon2id or bcrypt with per-user salt | AES, SHA-256, MD5, one global salt |
| Store an API token you must show again | Encrypt (AEAD) | Hash (you cannot show it) |
| Store an API token you only verify | Hash with HMAC or SHA-256 (high-entropy secret) | Encrypt |
| Search an email | Blind index (HMAC) | Plain SHA-256 |
| Verify a file or message was not altered | HMAC or AEAD tag | Bare checksum |
Data masking and dynamic masking Important
In plain words: masking changes what a reader sees (****-1234) without changing what is stored, or produces a safe fake copy for test systems.
Common misunderstanding: “Dynamic masking is encryption.” It is a display rule: the stored value is plaintext and a user with the UNMASK permission, or one who can guess through filters, still gets it. It reduces accidental exposure, not determined attackers.
| Product | Feature | What it does | Limits |
|---|---|---|---|
| SQL Server, Azure SQL | Dynamic Data Masking (MASKED WITH (FUNCTION = 'partial(...)'), UNMASK permission) | Masks results for users without UNMASK | Inference through WHERE is possible; not a security boundary on its own |
| MySQL Enterprise | Data masking components and functions | Masks values in queries and generates masked data | Enterprise edition |
| PostgreSQL | postgresql_anonymizer extension (dynamic and static masking), or views with CASE per role, or RLS | Masks for roles, or rewrites a copy | Extension install; views must be the only access path |
| Oracle | Data Redaction | Redacts at query time | Licensed option |
| Application layer | Serializer or resource that hides fields | Per-API masking | Easy to forget in one endpoint |
| Non-production copies | Static masking or synthetic data | Real values never leave production | Covered in Database Security: masking |
Backups, WAL and cost
Backups and archives Must-know
In plain words: a backup is a second copy of everything, usually kept longer and guarded worse than the database. Encrypt it with a key that is not on the machine that made it.
Common misunderstanding: “Our volume is encrypted, so backups are covered.” A pg_dump or a pgBackRest repository in an S3 bucket needs its own encryption; a public bucket with plaintext dumps is the classic breach.
| Product | Backup encryption |
|---|---|
| PostgreSQL | pg_dump output piped through age or gpg; pgBackRest repository encryption (repo-cipher-type=aes-256-cbc, repo-cipher-pass); WAL archive encrypted by the tool; pg_tde backups with WAL encryption |
| MySQL | Percona XtraBackup --encrypt; MySQL Enterprise Backup encryption; binlog encryption (binlog_encryption=ON) |
| SQL Server | TDE-encrypted databases give encrypted backups; BACKUP ... WITH ENCRYPTION (ALGORITHM = AES_256, SERVER CERTIFICATE = ...) |
| Oracle | RMAN backup encryption (transparent, password or dual mode) |
| MongoDB | Encrypted storage engine data; mongodump output encrypted by the pipeline; Atlas encrypts snapshots |
| RDS / Aurora | Snapshots and backups of an encrypted instance are encrypted with the same KMS key |
| SQLite, Redis | Encrypt the copied file (age, gpg, volume) |
The restore drill that matters: restore on a clean host using only the documented key material. If it needs something that exists only on the dead server, the key loss scenario is already in your backup.
Performance cost Important
In plain words: modern CPUs encrypt at memory speed, so volume and TDE encryption cost little; what costs is key calls, round trips and lost query power.
Common misunderstanding: “TDE halves performance.” The vendor docs read for this page give no single figure: Amazon says a "minimal impact on performance", Oracle says "The actual performance impact on applications can vary", and Microsoft warns that tempdb encryption "might have a performance effect for unencrypted databases on the same SQL Server instance". Measure with your own workload.
| Cost source | What happens | How to measure and reduce |
|---|---|---|
| AES in the CPU (AES-NI on x86, ARMv8 crypto extensions) | Hardware rounds make block encryption cheap | Check the CPU flag (grep aes /proc/cpuinfo); Go's crypto/aes and OpenSSL use the instructions when present |
| TDE page encryption | Encrypt on write to disk, decrypt on read into the buffer pool; hot data in cache is plaintext | Run pgbench or sysbench before and after, compare p95 latency and CPU |
| KMS round trips | Network call per unwrap (milliseconds) | Cache unwrapped DEKs in memory for seconds; one DEK per tenant |
| Larger rows | Ciphertext is longer (nonce + tag, base64 if text) | TEXT or bytea; mind row size and TOAST |
| Lost indexes | Encrypted columns cannot use range indexes | Blind index for equality; separate plain derived columns for ranges |
| TLS | Handshake per connection, small per-byte cost | Pooling and reuse; session resumption; TLS 1.3 saves a round trip |
| Application encryption | CPU in the application tier | Scale horizontally; batch; avoid decrypting columns you do not need (select fewer columns) |
Compliance mapping
Mapping obligations to layers is the useful view; the full control table is in Database Security: compliance mapping. Clause numbers are given only where this page read the text.
| Framework | What the text asks for | Layers that answer it |
|---|---|---|
| GDPR Art. 32 | "the pseudonymisation and encryption of personal data" among measures appropriate to the risk | TDE and volume (at rest), TLS (transit), field encryption and pseudonymisation, crypto-shredding for erasure |
| HIPAA Security Rule 45 CFR 164.312 | "Encryption and decryption (Addressable). Implement a mechanism to encrypt and decrypt electronic protected health information." plus transmission security | TDE or volume, field encryption for ePHI, TLS verify-full; Addressable means document the decision if you do not implement it |
| PCI DSS v4.x | Protect stored account data and cardholder data in transit (requirement numbers not quoted here) | Tokenization or field encryption of the PAN, TDE as a supporting layer, TLS 1.2 or higher, key management with split knowledge and dual control |
| SOC 2 (Trust Services Criteria) | Encryption at rest and in transit as controls | Volume or TDE, TLS, KMS audit logs |
| Data residency and sovereignty | Control over who can access data and where | Client-side keys held in-country (HYOK), confidential computing with attestation, regional KMS |
| Compliance question | Honest answer |
|---|---|
| "Is TDE enough for PCI?" | It protects stored data against media theft; many assessors expect the PAN itself to be unreadable even to DBAs, which means tokenization or application encryption on top |
| "Does encrypting at rest satisfy erasure requests?" | No; erasure needs deletion or crypto-shredding of the specific person's data |
| "Can we skip TLS inside the VPC?" | Check the standard; ePHI and cardholder data in transit are expected to be protected, and internal networks are not trusted by default |
Per-engine behaviour
What each database really offers
| Product | Encryption at rest | Column / field | In transit | Client-side / in use | Key management |
|---|---|---|---|---|---|
| PostgreSQL | None in core; volume encryption; pg_tde in Percona Server for PostgreSQL | pgcrypto (server-side), application-side | SSL/TLS (sslmode, hostssl), GSSAPI encryption, mTLS with clientcert | Client-side by design; run in a Confidential VM | Your own; KMS through pg_tde key providers |
| MySQL 8.4 / InnoDB | Tablespace encryption with keyring master key; redo, undo, binlog encryption options | AES_ENCRYPT() (server-side, key in SQL), application-side | TLS (require_secure_transport, REQUIRE X509) | Application-side; Confidential VM | Keyring component: file (all editions), encrypted file, KMIP, AWS, others (Enterprise) |
| SQL Server | TDE (AES), backup encryption | Always Encrypted (client-side), cell-level ENCRYPTBYKEY | TLS (Encrypt, TrustServerCertificate) | Always Encrypted with secure enclaves (VBS) | Certificates, EKM, Azure Key Vault, HSM |
| Oracle | TDE tablespace and column encryption, RMAN backups | TDE column encryption, DBMS_CRYPTO | Native network encryption and TLS | Data Redaction (display), Database Vault | Keystore: software wallet, HSM, Oracle Key Vault; ADMINISTER KEY MANAGEMENT |
| MongoDB | Encrypted Storage Engine (Enterprise, WiredTiger), Atlas default | CSFLE (field), Queryable Encryption | TLS (requireTLS), x.509 | CSFLE and QE are client-side | KMIP, AWS/Azure/GCP KMS |
| SQLite | None in core; SQLCipher or SEE (third-party) | Application-side | Not applicable (embedded) | Not applicable | Application |
| CockroachDB | Enterprise encryption at rest (verify in its docs), volume | Application-side | TLS required by default in secure mode (verify) | Application-side | Store key files or KMS |
| Redis | None in open source; managed services at the volume level | Application-side (values are opaque bytes) | TLS (tls-port), mTLS | Not applicable | Service or application |
| AWS RDS / Aurora | Volume and snapshot encryption with KMS (AES-256) | Same as the engine | Per-engine TLS; the in-region replication link is encrypted | Application-side | AWS KMS key per instance |
Defaults that bite
| Default | Engine | Consequence |
|---|---|---|
sslmode=prefer | libpq, Laravel pgsql | Falls back to plaintext silently; not verified |
| No TLS configured | PostgreSQL, MySQL, Redis out of the box | Plaintext on the wire until you enable it |
innodb_redo_log_encrypt off | MySQL | Redo log holds plaintext even if tablespaces are encrypted |
| TDE off | SQL Server, Oracle | Nothing is encrypted until enabled |
ENCRYPTION default off | MySQL tables | Needs ENCRYPTION='Y' or schema default DEFAULT ENCRYPTION='Y' |
pgp_sym_encrypt default cipher | pgcrypto | Defaults to AES-128 unless cipher-algo=aes256 |
local keyring file | MySQL component_keyring_file | Master key sits on the same host as the data |
| Rotation off | KMS keys | Enable automatic rotation or plan manual rotation |
Mechanics
Every knob in one table Must-know
| Setting | Product | Meaning |
|---|---|---|
ssl, ssl_cert_file, ssl_key_file, ssl_ca_file, ssl_crl_file | PostgreSQL server | Turn TLS on; trust anchors; revocation |
ssl_min_protocol_version, ssl_max_protocol_version, ssl_ciphers | PostgreSQL server | Protocol and cipher policy; default minimum TLSv1.2 |
sslmode, sslrootcert, sslcert, sslkey, sslcrl | libpq client | Verification level and certificates |
clientcert=verify-ca / verify-full | pg_hba.conf | Require and verify client certificates |
password_encryption = scram-sha-256 | PostgreSQL | Hash format for role passwords |
CREATE EXTENSION pgcrypto | PostgreSQL | Hashing, HMAC, PGP functions |
require_secure_transport, tls_version, ssl_ca, ssl_cert, ssl_key | MySQL | TLS enforcement and files |
ENCRYPTION='Y', default_table_encryption, innodb_redo_log_encrypt, innodb_undo_log_encrypt, binlog_encryption | MySQL | What is encrypted at rest |
ALTER INSTANCE ROTATE INNODB MASTER KEY, ALTER INSTANCE RELOAD TLS | MySQL | Key and certificate rotation |
CREATE DATABASE ENCRYPTION KEY, ALTER DATABASE ... SET ENCRYPTION ON, sys.dm_database_encryption_keys | SQL Server | TDE |
ADMINISTER KEY MANAGEMENT, ENCRYPTION USING 'AES256' | Oracle | Keystore and encrypted tablespaces |
security.enableEncryption, encryptionCipherMode, encryptionKeyFile, kmip.* | MongoDB mongod | Encrypted Storage Engine |
client_tls_sslmode, server_tls_sslmode, *_tls_ca_file | PgBouncer | Pooler TLS on both legs |
APP_KEY, APP_PREVIOUS_KEYS, cipher in config/app.php | Laravel | Encrypter key, rotation, AES-256-CBC or AES-256-GCM family |
Error codes and messages you will see Important
| Message or class | From | Meaning | Fix |
|---|---|---|---|
SSL error: certificate verify failed | libpq | Chain not trusted by sslrootcert | Install the right CA; do not drop to require |
server certificate for "db-lab" ... does not match host name "172.18.0.2" | libpq verify-full | Connected by a name missing from the certificate SAN | Use the DNS name in the certificate, or reissue |
server does not support SSL, but SSL was required | libpq | Server TLS off, client demanded it | Enable ssl = on or fix the host |
pg_hba.conf rejects connection for host ..., no encryption | PostgreSQL | A hostssl line exists and the client used plaintext | Set sslmode=require or stronger |
MySQL 3159 ER_SECURE_TRANSPORT_REQUIRED | MySQL | require_secure_transport=ON and the client used plaintext | Connect with TLS |
Wrong key or corrupt data | pgp_sym_decrypt | Wrong key or damaged ciphertext | Check key version; restore from backup |
Cannot find server certificate with thumbprint ... | SQL Server restore | TDE certificate missing on the new server | Restore certificate and private key first |
Illuminate\Contracts\Encryption\DecryptException ("The MAC is invalid.") | Laravel | Wrong APP_KEY, tampered or truncated ciphertext | Add the old key to APP_PREVIOUS_KEYS |
cipher: message authentication failed | Go crypto/cipher | AEAD tag mismatch: wrong key, wrong AAD, modified data | Check key id, AAD (row identity), column truncation |
InvalidCiphertextException, KMSInvalidStateException, DisabledException, AccessDeniedException | AWS KMS | Bad blob or wrong key; key pending deletion; key disabled; IAM denies | Fix key id and policy; cancel deletion in time |
How a read works through each layer
SELECT email FROM customer WHERE email_bidx = $1 (Laravel/Go with application-side encryption, TDE on, TLS verify-full)
1 app computes HMAC blind index (application memory)
2 TLS record encrypted to the pooler (PgBouncer terminates, opens second TLS leg to PostgreSQL)
3 PostgreSQL index lookup on email_bidx (pages come from shared_buffers; plaintext pages if TDE, ciphertext of fields always)
4 page missing in cache -> read from volume (LUKS/EBS decrypts blocks transparently)
5 row returned: email_enc = nonce || ct || tag (server never held the data key)
6 app asks KMS to unwrap the DEK (or uses a cached DEK), AES-GCM open, tag verified
7 plaintext email used in the request, DEK zeroed or cached for seconds
-- every arrow crosses a different trust boundary; each boundary needs its own key and its own audit trailSolving the classic problems
A stolen backup or snapshot
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Encrypt backups with a KMS key and keep the key elsewhere | pgBackRest repo encryption, BACKUP ... WITH ENCRYPTION, RMAN | Stolen file is noise | Key custody, restore drills |
| Field-level encryption of the sensitive columns | Laravel casts, Always Encrypted, CSFLE | Even a plaintext dump has no secrets | Search and reporting limits |
| Short retention plus crypto-shredding by tenant | KEK per tenant, destroy to delete | Meets erasure in backups | Operational maturity |
A DBA or a cloud operator must not read the data
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Client-side keys | Laravel encrypted, Always Encrypted, CSFLE, tink-go | Server never has plaintext | Application becomes the trust anchor |
| Confidential VM with attestation | SEV-SNP or TDX plus key release after attestation | Unchanged SQL and indexes | Trust in the CPU vendor and in your image |
| Separation of duties and audit | Different people for DB and key admin, pgAudit | Cheap, procedural | Not cryptographic |
Search on an encrypted column
| Need | Solution | Limit |
|---|---|---|
| Equality (email, national ID) | Blind index (HMAC) or deterministic encryption | Leaks equality |
| Prefix search | Several truncated blind indexes (first 3 letters) | Leaks the short values; limited |
| Range, sort | Enclave (Always Encrypted), Queryable Encryption, or a plaintext coarse bucket (age band) | Hardware trust, or deliberate leakage |
| Full text | Do not encrypt; move to a separate indexed store with its own protection | Policy decision |
// Go: read path of the blind-index search. The data key never reaches PostgreSQL.
func (r *Repo) FindByEmail(ctx context.Context, email string) (*Customer, error) {
idx := BlindIndex(r.blindKey, "email", email, 16)
rows, err := r.db.QueryContext(ctx, `SELECT id, email_enc, wrapped_dek FROM customer WHERE email_bidx = $1`, idx)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() { // several rows when truncation made values collide
var id int64
var enc, wrapped []byte
if err := rows.Scan(&id, &enc, &wrapped); err != nil {
return nil, err
}
plain, err := Open(ctx, r.kms, Envelope{KeyID: r.keyID, WrappedDEK: wrapped, Ciphertext: enc}, aadFor(id, "email"))
if err == nil && strings.EqualFold(string(plain), strings.TrimSpace(email)) {
return &Customer{ID: id, Email: string(plain)}, nil
}
}
return nil, sql.ErrNoRows
}Rotating the application key without downtime
| Step | Action | Safe to stop here? |
|---|---|---|
| 1 | Generate the new key, set APP_KEY new and APP_PREVIOUS_KEYS old | Yes (reads work, new writes use new key) |
| 2 | Run crypto:reencrypt in chunks | Yes (idempotent) |
| 3 | Query for rows still failing under the new key only | Yes |
| 4 | Remove the old key | No: irreversible without a backup of the old key |
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
/**
* Re-encrypts stored values under the current APP_KEY after a rotation.
* Run it while APP_PREVIOUS_KEYS still lists the old key; remove the old key
* only after this command has finished and a verification query finds nothing left.
*/
class RotateEncryptedColumns extends Command
{
protected $signature = 'crypto:reencrypt {--chunk=500}';
protected $description = 'Re-encrypt customers.email and customers.national_id under the current key';
public function handle(): int
{
$done = 0;
DB::table('customers')->orderBy('id')->chunkById((int) $this->option('chunk'), function ($rows) use (&$done): void {
foreach ($rows as $row) {
$update = ['email' => Crypt::encryptString(Crypt::decryptString($row->email))];
if ($row->national_id !== null) {
$update['national_id'] = Crypt::encryptString(Crypt::decryptString($row->national_id));
}
// Raw update on purpose: through Eloquent the model would see
// equal plaintext, report no change, and skip the write.
DB::table('customers')->where('id', $row->id)->update($update);
$done++;
}
});
$this->info("Re-encrypted {$done} rows.");
return self::SUCCESS;
}
}Deleting a person or tenant from immutable storage
Use a KEK per tenant or per data subject (or a DEK per record in a small table), keep wrapped DEKs with the data, and destroy the KEK. The Go Rewrap and the stub DestroyKey in the envelope snippet show the shape; in a cloud KMS you schedule key deletion with a waiting period, which doubles as your undo window.
The key leaked, now what
| Key | Immediate action | Follow-up |
|---|---|---|
| DEK of one record or tenant | Re-encrypt that data under a new DEK | Review who could call Decrypt |
| KEK | Create a new version, rewrap all DEKs, disable the old version | Audit KMS logs for the exposure window |
APP_KEY | Rotate with APP_PREVIOUS_KEYS, re-encrypt, invalidate sessions and signed URLs | Cookies and other encrypted payloads also use this key |
| Blind-index key | Recompute every index | Equality leaks for the period are permanent |
| TLS private key | Reissue and reload certificates, revoke | ssl_crl_file, short-lived certificates |
Choosing
| Situation | Recommended layer | Extra technique | Reason |
|---|---|---|---|
| Any production database | Volume or cloud-managed encryption + TLS verify-full | Encrypted backups, key in KMS | Baseline everyone expects |
| Auditor asks "encryption at rest" on SQL Server, Oracle, MySQL | TDE | Keep certificate backups, test restore | Satisfies the checkbox, cheap |
| PostgreSQL with that requirement | Volume encryption (or pg_tde on Percona) | WAL and temp-file coverage check | Core has no TDE |
| National ID, card number, health notes | Application-side randomised encryption | Blind index for lookups; tokenization for cards | DBA and backup also covered |
| Multi-tenant SaaS with enterprise customers | KEK per tenant, optionally customer-managed (BYOK) | Crypto-shredding on offboarding | Per-tenant erasure and trust |
| Host or cloud operator is the adversary | Confidential VM with attestation | Client-side keys for the crown jewels | Protects data in use |
Need range and LIKE on encrypted data | SQL Server enclaves or MongoDB Queryable Encryption | Accept the leakage profile | Server-side query power |
| Private sums over a few values | PHE (Paillier) or CKKS | Do it in a small service | FHE for general SQL is not practical |
| Passwords | argon2id (or bcrypt) | Pepper, rate limits | Never reversible |
| Non-production data | Masked or synthetic copy | No production dumps | Removes the risk instead of encrypting it |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel monolith with PostgreSQL on one RDS instance: turn on RDS storage encryption with a KMS key, set DB_SSLMODE=verify-full with the RDS CA bundle, mark national_id and phone as encrypted in the model casts, add a blind index for the email lookup, and keep APP_KEY in the secrets manager, not in the repository. One key hierarchy, one place to rotate. The simplest correct set is volume + TLS + a few encrypted fields.
Modular monolith and multiple databases
Each module owns its schema and, ideally, its own KEK and blind-index key, so the billing module can decrypt card tokens and the support module cannot. Shared libraries (an EncryptedField cast, a BlindIndex helper, a KmsClient) live in a shared kernel; keys do not. Every database gets its own TLS settings and its own TDE or volume key. A reporting database fed by replication needs the same protection as the primary or must receive pseudonymised data only.
Microservices
Checkout service Vault / KMS Payments service Orders DB
1 PAN arrives over TLS 1.3
2 POST /tokenize ---------> vault transit tokenize (PAN never stored in checkout)
3 <-------------- token tok_8f3c...
4 publish OrderPlaced {token} to the broker (see messaging security)
5 consume event, detokenize via KMS policy
6 charge the card, store only the token in Orders DB
-- services that see only tokens are out of PCI scope; each service has its own KMS IAM role and keyService-to-service TLS is usually mTLS handled by the mesh or by the libraries (mTLS Service Security); per-service database credentials and per-service keys keep a breach of one service from decrypting another's data. Events carrying personal data should carry tokens or encrypted payloads, and the erasure story must reach the broker's retention, covered in the messaging security chapter.
Distributed data: replicas, caches and shards
Replicas are full copies: encrypt each one (TDE or volume), use verify-full in primary_conninfo, and remember that a TDE key must exist on every node (SQL Server certificates have to be copied to secondaries and restored on failover targets). Caches (Redis, Memcached) hold plaintext copies unless the application encrypts values before SET; cache keys must not contain personal data. Shards can have a key per shard or tenant, which makes moving a tenant a rewrap, not a re-encryption. Multi-region: use a regional KMS key per region (or a multi-Region key) and check where decrypt calls are allowed to run; cross-region replication of encrypted storage re-encrypts under the destination key. Read replicas and analytic copies are where ungoverned plaintext tends to accumulate: Replication and OLTP vs OLAP decide which copies exist.
Scaling path: 1×, 10×, 100×
| Load | What changes | Example |
|---|---|---|
| 1× | Managed encryption, TLS, a handful of encrypted fields, one KMS key | Startup on RDS with Laravel casts |
| 10× | KMS call rates and latency matter: DEK per tenant with in-memory caching, blind-index columns indexed, background re-encryption jobs | Cache unwrapped DEKs for 60 seconds, batch GenerateDataKey |
| 100× | Per-tenant KEKs and customer-managed keys, HSM-backed KMS, dedicated crypto service (Vault transit or a sidecar), rotation as a pipeline, attested confidential nodes for the most sensitive tier | Enterprise SaaS with BYOK and crypto-shredding on contract end |
| Any | Key loss, audit and restore drills never become optional | Quarterly restore on a clean host using only documented key material |
Lab
Six experiments. They need Docker and openssl. The Go step (Experiment 5) was run when this page was written. The PostgreSQL and sslmode steps could not be executed here (the Docker daemon was not running), so the output blocks show the expected shape, not captured output, and your IPs and ciphertext bytes will differ; run them and compare. The Laravel step is compile-only (no PHP on the authoring machine).
Experiment 1: pgcrypto column + blind index (PostgreSQL 17)
docker run -d --name enc-pg -e POSTGRES_PASSWORD=lab postgres:17
export DEK=$(openssl rand -base64 32) BIDX=$(openssl rand -base64 32)
docker cp docs/snippets/database/encryption-in-use/sql/pgcrypto-column.sql enc-pg:/tmp/
docker exec -e PGPASSWORD=lab enc-pg psql -U postgres -v dek="$DEK" -v bidx="$BIDX" -f /tmp/pgcrypto-column.sql distinct_ciphertexts | distinct_blind_indexes
----------------------+------------------------
2 | 1 <- randomised ciphertext, one searchable fingerprint
id | name | email
----+------------+-----------------
1 | Ann | Ann@Example.com <- search term was " ann@example.com " (normalised)
2 | Ann (copy) | Ann@Example.comExperiment 2: wrong key and tampering
SELECT pgp_sym_decrypt(email_enc, 'not-the-key') FROM customer LIMIT 1;
-- ERROR: Wrong key or corrupt data
SELECT email_enc FROM customer WHERE id = 1; -- raw bytea: what a DBA or a leaked dump seesExperiment 3: the key is visible to the server
SELECT pid, query FROM pg_stat_activity WHERE query LIKE '%pgp_sym_encrypt%';
-- in another session, while a long INSERT runs: the statement text, with the key, is visible to a superuserExperiment 4: sslmode levels, with no attacker. Run the script; it creates a CA, a certificate valid only for the name db-lab, a hostssl-only server, and connects five ways.
#!/usr/bin/env bash
# Lab: sslmode levels against a throwaway PostgreSQL, no attacker needed.
# verify-full is shown by connecting to the same server under a name that is
# NOT in the certificate (its IP address). Requires docker and openssl.
set -euo pipefail
WORK=$(mktemp -d); cd "$WORK"
NET=encl-net; DB=db-lab
# 1. A private CA and a server certificate whose SAN lists only the name "db-lab".
openssl req -x509 -newkey rsa:2048 -nodes -days 7 -subj "/CN=lab-ca" -keyout ca.key -out ca.pem
openssl req -newkey rsa:2048 -nodes -subj "/CN=$DB" -keyout server.key -out server.csr
printf "subjectAltName=DNS:%s\n" "$DB" > san.ext
openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 7 -extfile san.ext -out server.pem
# 2. hostssl only: a plaintext connection is rejected by pg_hba.conf.
cat > hba.conf <<'H'
local all all trust
hostssl all all all scram-sha-256
host all all all reject
H
docker network create $NET >/dev/null
trap 'docker rm -f $DB >/dev/null 2>&1; docker network rm $NET >/dev/null 2>&1' EXIT
docker run -d --name $DB --network $NET -e POSTGRES_PASSWORD=lab \
-v "$WORK":/certs:ro --entrypoint bash postgres:17 -c '
cp /certs/server.pem /certs/server.key /certs/hba.conf /var/lib/postgresql/ &&
chown postgres:postgres /var/lib/postgresql/server.* /var/lib/postgresql/hba.conf &&
chmod 600 /var/lib/postgresql/server.key &&
exec docker-entrypoint.sh postgres -c ssl=on \
-c ssl_cert_file=/var/lib/postgresql/server.pem -c ssl_key_file=/var/lib/postgresql/server.key \
-c hba_file=/var/lib/postgresql/hba.conf' >/dev/null
until docker exec $DB pg_isready -q; do sleep 1; done
IP=$(docker inspect -f '{{(index .NetworkSettings.Networks "'$NET'").IPAddress}}' $DB)
psqlc() { # usage: psqlc <host> <sslmode>
# With a root certificate present, libpq treats "require" like verify-ca, so
# the CA file is only passed to the verify-* modes.
local root=""; case "$2" in verify-*) root="sslrootcert=/certs/ca.pem";; esac
docker run --rm --network $NET -v "$WORK":/certs:ro -e PGPASSWORD=lab postgres:17 \
psql "host=$1 user=postgres dbname=postgres sslmode=$2 $root" \
-tAc "select 'ssl=' || ssl || ' ' || version || ' ' || cipher from pg_stat_ssl where pid = pg_backend_pid()" 2>&1 || true
}
echo "--- disable (plaintext, pg_hba rejects)"; psqlc $DB disable
echo "--- require (encrypted, nothing verified)"; psqlc $DB require
echo "--- verify-ca (chain verified, by IP)"; psqlc $IP verify-ca
echo "--- verify-full (right name: db-lab)"; psqlc $DB verify-full
echo "--- verify-full (wrong name: the IP)"; psqlc $IP verify-full--- disable (plaintext, pg_hba rejects)
psql: error: connection to server at "db-lab" (172.18.0.2), port 5432 failed: FATAL: pg_hba.conf rejects connection for host "172.18.0.3", user "postgres", database "postgres", no encryption
--- require (encrypted, nothing verified)
ssl=t TLSv1.3 TLS_AES_256_GCM_SHA384
--- verify-ca (chain verified, by IP)
ssl=t TLSv1.3 TLS_AES_256_GCM_SHA384
--- verify-full (right name: db-lab)
ssl=t TLSv1.3 TLS_AES_256_GCM_SHA384
--- verify-full (wrong name: the IP)
psql: error: connection to server at "172.18.0.2", port 5432 failed: server certificate for "db-lab" does not match host name "172.18.0.2"The last line is the proof: the same server, the same certificate, the same CA, and the only change is the name the client used. A man-in-the-middle presenting any other certificate fails the same check, which require would have accepted. Cleanup: the script removes its container and network; docker rm -f enc-pg removes Experiment 1.
Experiment 5: Go envelope encryption, crypto-shredding and the blind index
cd docs/snippets/database/encryption-in-use/go && go run ./envelope && go run ./blindindex
# round trip: 0012345678
# moved to another row: true <- AAD binds the ciphertext to its row
# after rewrap to tenant-42/v2: 0012345678
# after crypto-shredding: unwrap data key: kms: key "tenant-42/v2" does not exist or was destroyedExperiment 6: Laravel encrypted cast round trip (compile-only)
Copy Customer.php, BlindIndex.php, the migration and the feature test into a Laravel 13 app, set BLIND_INDEX_KEY (openssl rand -base64 32) in .env, add 'blind_index' => ['key' => env('BLIND_INDEX_KEY')] to config/services.php, and run php artisan test --filter=EncryptedCastRoundTrip. The test reads the row with DB::table to prove the stored value is ciphertext and finds it again through whereEmailIs().
<?php
namespace Tests\Feature;
use App\Models\Customer;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class EncryptedCastRoundTrip extends TestCase
{
use RefreshDatabase;
public function test_value_is_ciphertext_in_the_database_and_plaintext_in_the_model(): void
{
$customer = Customer::create(['name' => 'Ann', 'email' => 'Ann@Example.com', 'national_id' => '0012345678']);
// Raw read: what a DBA or a leaked dump sees.
$raw = DB::table('customers')->where('id', $customer->id)->first();
$this->assertNotSame('Ann@Example.com', $raw->email);
$this->assertStringNotContainsString('Example', $raw->email);
// Model read: the cast decrypts transparently.
$this->assertSame('Ann@Example.com', Customer::find($customer->id)->email);
}
public function test_blind_index_finds_the_row_and_is_case_insensitive(): void
{
Customer::create(['name' => 'Ann', 'email' => 'Ann@Example.com']);
$found = Customer::whereEmailIs(' ann@example.com ')->first();
$this->assertNotNull($found);
$this->assertSame('Ann@Example.com', $found->email);
}
}Common misconceptions
| Belief | Reality |
|---|---|
| "The disk is encrypted, so the data is safe" | Only against theft of the disk; every logged-in session and every backup copy sees plaintext |
| "TDE protects me from the DBA" | TDE decrypts for every authorised query; use client-side encryption for that threat |
"sslmode=require is secure" | It encrypts but does not verify who answered; use verify-full |
| "HTTPS covers my database traffic" | The app-to-database link is a separate connection with its own setting |
"Encrypted columns can be searched with WHERE" | Only through a blind index, deterministic encryption or an enclave |
| "A SHA-256 of the email is a safe index" | Guessable inputs are reversible by dictionary; use HMAC with a secret key |
| "Deterministic encryption has the same secrecy as randomised" | It leaks equality and frequency |
| "pgcrypto keeps the key from the server" | The key and plaintext pass through the server in clear |
| "Rotating the KMS key re-encrypts my data" | New versions apply to new operations; old data needs rewrap or re-encryption |
| "Passwords can be stored encrypted" | Hash with argon2id or bcrypt; reversibility is a vulnerability |
| "Homomorphic encryption lets me run any query encrypted" | Only limited operations, with heavy overhead and large ciphertexts |
| "Confidential computing makes bugs irrelevant" | It protects from the host, not from flaws in code that is allowed to read the data |
| "If I lose the key I can ask the vendor" | There is no recovery path; key loss is data loss |
Cheat sheet
| Topic | What to remember |
|---|---|
| Start from the attacker | Disk thief, backup leak, sniffer, DBA, memory dump, cloud operator: one layer each |
| Volume and TDE | Protect media, not logins; cheap; transparent |
| PostgreSQL | No TDE in core; use volume encryption or pg_tde on Percona; pgcrypto passes the key through the server |
| Envelope encryption | DEK encrypts data, KEK wraps DEK, KMS/HSM holds the KEK; rotate by rewrap |
| GCM | Fresh nonce per message, at most 2^32 random-nonce messages per key; bind AAD to the row |
| TLS | verify-full (or MySQL VERIFY_IDENTITY), minimum TLS 1.2, cover replication and poolers |
| mTLS | clientcert=verify-full in pg_hba.conf; REQUIRE X509 in MySQL |
| Searchable | Blind index = HMAC with its own key; equality only; truncate to blur |
| Deterministic | Equality works, frequency leaks; avoid on low cardinality |
| Client-side | Laravel encrypted, Always Encrypted, CSFLE, Queryable Encryption: the server never has the key |
| In use | Confidential VM (SEV-SNP, TDX) with attestation; SGX for enclaves; HE only for small jobs |
| Passwords | argon2id or bcrypt, never encryption |
| Masking | Display rule, not encryption |
| Backups | Encrypt separately; test restore with documented keys only |
| Key loss | Data loss; crypto-shredding is deletion on purpose |
| Compliance | GDPR Art. 32 names encryption and pseudonymisation; HIPAA encryption is Addressable; map every rule to a layer |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A laptop with an encrypted disk is stolen while the database was running and logged in. Is the data safe? Which layer would have helped? Must-know
Answer
Answer: Not necessarily: if the volume was mounted and unlocked, the data is readable, and cold-boot or live attacks can reach keys in RAM. Disk encryption stops theft of a powered-off device. Short screen locks, memory protection and client-side field keys cover the running case.
2 — Why does TDE not stop a DBA from reading a customer's card number? Must-know
Answer
Answer: The engine decrypts pages into the buffer pool for every authorised session, so SELECT returns plaintext. TDE protects the files, not the logins; use client-side field encryption or tokenization.
3 — What exactly does PostgreSQL offer for encryption at rest? Important
Answer
Answer: No built-in TDE. Options: volume or file-system encryption, pg_tde on Percona Server for PostgreSQL, pgcrypto for chosen columns, and application-side encryption.
4 — Explain envelope encryption and why rotation of the KEK is cheap. Important
Answer
Answer: A data key encrypts the data and is stored wrapped by a KEK held in a KMS or HSM. Rotating the KEK rewraps the small wrapped data keys; the data is not re-encrypted.
5 — Why is sslmode=require not enough, and what is the single change that fixes it? Must-know
Answer
Answer: It encrypts without verifying the server, so a man-in-the-middle can present any certificate. Use verify-full with the right CA so the chain and host name are checked.
6 — How can you search an encrypted email column, and what does it leak? Important
Answer
Answer: Store a keyed HMAC of the normalised email in an indexed column and search by the HMAC of the term. It leaks which rows have equal values; truncation and a separate key reduce that.
7 — When is deterministic encryption a bad idea? Important
Answer
Answer: On low-cardinality columns (booleans, countries, statuses) because equal ciphertexts reveal frequencies and can be matched to known distributions.
8 — Why must passwords be hashed rather than encrypted, and with what? Must-know
Answer
Answer: Encryption is reversible, so a key leak exposes every password. Use a slow salted hash such as argon2id or bcrypt.
9 — What does confidential computing protect, and what does it not? Good to know
Answer
Answer: It encrypts memory of a VM or enclave against the host, hypervisor and memory dumps, and provides attestation. It does not protect against flaws in code inside the enclave or against a legitimate but malicious SQL user.
10 — A customer exercises erasure but their data is in year-old backups. What do you do? Important
Answer
Answer: If their data was encrypted under a key that belongs only to them (or their tenant), destroy that key (crypto-shredding). The backups remain but are unreadable for that data.
11 — After rotating APP_KEY, some rows fail to decrypt. What happened? Important
Answer
Answer: The old key was not listed in APP_PREVIOUS_KEYS (or was removed before re-encryption finished), so Laravel could not decrypt old ciphertext and threw DecryptException.
12 — Which of PHE, SHE and FHE would you consider for encrypted SUM over a few thousand rows? Good to know
Answer
Answer: PHE (Paillier addition) is the practical choice; SHE or CKKS if you need limited multiplications; FHE with bootstrapping is too heavy for general SQL.
Glossary
| Term | Meaning |
|---|---|
| AAD (additional authenticated data) | Data bound into an AEAD tag but not encrypted, such as table, column and row id |
| AEAD | Authenticated encryption with associated data (AES-GCM, ChaCha20-Poly1305) |
| AES-GCM | Counter-mode AES with a Galois authentication tag; NIST SP 800-38D |
| AES-NI | CPU instructions that accelerate AES |
| Attestation | Cryptographic proof of what code and hardware a VM or enclave is running |
| Blind index | Keyed HMAC of a value stored for equality search |
| BYOK / HYOK | Bring your own key / hold your own key (key stays outside the provider) |
| CEK / CMK | Column encryption key / column master key in SQL Server Always Encrypted |
| Confidential computing | Hardware-protected memory for data in use (SEV-SNP, TDX, SGX) |
| Crypto-shredding | Deleting data by destroying its key |
| Cryptoperiod | Time span a key is authorised for use (NIST SP 800-57) |
| CSFLE | MongoDB Client-Side Field Level Encryption |
| Deterministic encryption | Same plaintext always gives the same ciphertext |
| DEK | Data-encryption key |
| Envelope encryption | Encrypting data with a DEK and wrapping the DEK with a KEK |
| FHE / SHE / PHE | Fully, somewhat and partially homomorphic encryption |
| Format-preserving encryption (FPE) | Encryption whose output has the same format as the input (FF1, FF3-1) |
| HMAC | Hash-based message authentication code, a keyed hash |
| HSM | Hardware security module holding keys in tamper-resistant hardware |
| KEK | Key-encryption key that wraps DEKs |
| KMS | Key management service (AWS KMS, Cloud KMS, Azure Key Vault) |
| mTLS | Mutual TLS: both sides present certificates |
| Nonce / IV | Per-message value that must not repeat under the same key |
| Queryable Encryption | MongoDB scheme supporting queries over randomly encrypted fields |
| Randomised encryption | Same plaintext gives different ciphertext each time |
sslmode | libpq setting for TLS usage and verification |
| TDE | Transparent Data Encryption: engine-level file encryption |
| Tokenization | Replacing a value with a random token mapped in a vault |
| Wrapped key | A key encrypted by another key |
References
- PostgreSQL documentation: Encryption Options, pgcrypto, libpq SSL Support, Secure TCP/IP Connections with SSL, Connection settings, Replication settings; PostgreSQL wiki: Transparent Data Encryption; Percona: pg_tde README, documentation
- MySQL 8.4 Reference Manual (read via web.archive.org): InnoDB Data Encryption, Keyring Component Installation, Using Encrypted Connections
- Microsoft Learn: Transparent data encryption, Always Encrypted, Always Encrypted with secure enclaves
- Oracle: Introduction to Transparent Data Encryption (19c)
- MongoDB: Encryption at Rest, Client-Side Field Level Encryption, CSFLE encryption algorithms, Queryable Encryption
- AWS: KMS developer guide: data keys, KMS concepts, Encrypting Amazon RDS resources; HashiCorp: Vault transit secrets engine
- Confidential computing: Google Cloud Confidential VM overview, Intel SGX overview
- Homomorphic encryption: Microsoft SEAL README, HElib README
- NIST: SP 800-57 Part 1 Rev. 5, SP 800-38D (GCM)
- Laravel 13: Encryption, Eloquent mutators and casting; Go: crypto/cipher, Tink for Go
- PgBouncer: config; OWASP: Password Storage Cheat Sheet; GDPR Art. 32; HIPAA 45 CFR 164.312