Skip to content

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 forGo to
Three tables you can memoriseEverything in one minute
Why encryption has layers, and the vault analogyWhy it exists
Who invented what, and which feature arrived whenWhere it comes from
Which attacker each layer stopsThreat model per layer
LUKS, EBS/RDS, TDE in SQL Server, Oracle, MySQL, MongoDB; PostgreSQL has noneEncryption at rest
DEK, KEK, envelope encryption, KMS, HSM, rotation, key loss, crypto-shreddingKeys and key hierarchy
TLS 1.2/1.3, sslmode, mTLS, replication, PgBouncerEncryption in transit
pgcrypto, deterministic vs randomised, blind index, tokenization, FPEColumn and application-level encryption
MongoDB CSFLE and Queryable Encryption, SQL Server Always EncryptedClient-side field-level encryption
SEV-SNP, TDX, SGX, attestation, PHE/SHE/FHEEncryption in use
Passwords, argon2id, bcrypt, dynamic data maskingHashing, passwords and masking
Backups, WAL, temp files, performance and AES-NIBackups, WAL and cost
PCI DSS, GDPR, HIPAA mapped to layersCompliance mapping
Engine by engine, knobs, error messagesPer-engine behaviour, Mechanics
Fixes with SQL, Go and LaravelSolving the classic problems
Which layer for which situationChoosing
Monolith to microservices to multi-regionIn architecture
Reproduce it: pgcrypto, blind index, sslmode, Laravel castLab

Everything in one minute ​

The layers. Each row is unpacked in its own section.

LayerWhat is encryptedWho holds the keyStopsDoes not stop
Volume / disk (LUKS, dm-crypt, EBS, RDS storage)Every block, below the file systemOS, or the cloud KMSStolen disk, discarded hardwareAnyone logged in to the running server, a stolen database login
TDE (SQL Server, Oracle, MySQL InnoDB, MongoDB Enterprise, pg_tde)Data files, log, often backupsThe engine, with a master key in a keystore or KMSStolen files and backup mediaA DBA who can run SELECT
TLS (sslmode=verify-full, require_secure_transport)Bytes on the wireThe two endpoints' certificatesSniffing, man-in-the-middleAnything once the data reaches the server
Column encryption in the database (pgcrypto)Chosen columnsA key the client sends to the serverCasual readers of the tableA 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 themThe application, backed by a KMSDBA, backup thief, cloud operatorA compromised application server
Confidential computing (SEV-SNP, TDX, SGX)Memory of a VM or enclave while runningThe CPUHost admin, hypervisor, memory dumpBugs inside the protected code, side channels
Homomorphic encryption (PHE, SHE, FHE)Values, even while computed onThe data ownerThe server learns nothingCost: slow, large, limited operations

The words people mix up.

TermOne-line meaningReversible?Typical use
EncryptionScramble with a key; the key unscramblesYes, with the keyCard numbers, national IDs, tokens
HashingOne-way fingerprintNoPasswords (slow hashes), integrity checks
HMACHash with a secret keyNoBlind index, signatures of cookies
Encoding (Base64, hex)Change the alphabet, no secretYes, by anyoneStoring bytes as text
TokenizationReplace a value with a random token; the mapping lives in a vaultYes, through the vaultPCI card numbers
MaskingShow a fake or partial valueNot from the maskNon-production copies, support screens
PseudonymisationReplace identifiers so the person is not directly identifiable (GDPR Art. 4 and 32)With extra information kept apartAnalytics

What each choice does to queries.

ChoiceEquality =Range, ORDER BYLIKEJoinsCost
Volume or TDENormalNormalNormalNormalSmall and constant
Randomised application encryptionNo (needs a blind index)NoNoNoYou search elsewhere
Deterministic encryptionYes (same ciphertext)NoNoEquality joinsLeaks equal values
Blind index next to randomised ciphertextYesNoNoEquality onlyOne extra indexed column
Order-preserving or enclave schemesYesYes (enclave)Yes (enclave)YesSpecial hardware or weaker secrecy
HomomorphicOnly supported arithmeticHardHardHardVery 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 changeApplication and queries change
Every SQL feature keeps workingSearch, sort, join, aggregate break or need tricks
Protects files and mediaProtects against the DBA and the provider too
A DBA or a stolen login reads plaintextEngine, backup and replica see only ciphertext
Cheap to operateKey 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 ​

  1. “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.
  2. “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 default prefer does not even verify the server.
  3. “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.

Diskserver theftBackupleakNetworksniffingDBAOS rootMemorydumpCloudproviderVolume (LUKS, EBS)coverednot coverednot coverednot coverednot coveredpartialTDE (engine files)coveredpartialnot coverednot coverednot coveredpartialBackup encryptionnot coveredcoverednot coverednot coverednot coveredpartialTLS (in transit)not coverednot coveredcoverednot coverednot coverednot coveredClient-side field keyscoveredcoveredcoveredcoveredcoveredcoveredConfidential VM / enclavenot coverednot coverednot coveredpartialcoveredcoveredA layer protects only the columns marked covered. TDE and volume keys are used by the engine for everyauthorised session, so they do nothing against a DBA or a stolen application login. Client-side keys coverthe most threats but cost searchability and need careful key custody.
AttackerWhat they can getLayers that helpLayers that do not
Disk or server thief, discarded driveRaw blocks of the data directoryVolume encryption, TDETLS, 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 controlBackup encryption, TDE (engine backups), client-side keysVolume encryption of the production server (the backup leaves it)
Network sniffer or man-in-the-middleQueries, results, sometimes passwordsTLS verify-full, mTLSEverything at rest
DBA or OS root insiderAnything the engine can read, the server's memory, the logs, pg_read_server_filesClient-side field encryption, separation of duties, audit (Database Security)TDE, volume encryption, server-side pgcrypto
Memory dump or cold-boot attackerKeys and plaintext pages in RAMConfidential computing, short key lifetimes, no swapTDE (pages are decrypted in the buffer pool)
Cloud provider operator, hypervisor, subpoenaEverything running on their hostsClient-side keys held by you (HYOK), confidential computing with attestationProvider-managed disk keys alone
Compromised applicationWhatever the application can decryptLeast privilege, per-tenant keys, auditAll 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".

text
     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 disk

Real 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.

ProductVolume-level optionNotes
PostgreSQLLUKS, geli, BitLocker, cloud volume encryptionThe manual's recommended route when you need encryption at rest and do not run pg_tde
MySQL, MongoDB, Oracle, SQL ServerThe same, in addition to their own TDEIndependent layer, different key
RDS, Aurora, Cloud SQL, Azure SQLOne checkbox plus a KMS keyAmazon RDS: choose encryption when the instance is created; the docs list limitations for existing unencrypted instances
SQLiteWhole-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
RedisVolume encryption of the RDB/AOF files; open-source Redis has no built-in at-rest encryptionManaged services (ElastiCache and others) add a flag
CockroachDBStore-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."

text
     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 encrypted

Real 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.

EngineFeature nameKey hierarchyCoversRotationGotchas (from the docs)
SQL Server, Azure SQLTDEService master key → certificate in master or EKM → DEK (AES-128/192/256)Data and log files, tempdb automatically, backups of the databaseRe-encrypt with a new DEK; certificate rotationNot available for master, model, msdb; replication does not replicate data encrypted; lose the certificate, lose the backups
OracleTDEKeystore (wallet or HSM) master key → table or tablespace keyColumn or whole tablespace; backupsADMINISTER KEY MANAGEMENT re-keyNeeds 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 InnoDBData-at-rest encryptionKeyring component master key → per-tablespace keyFile-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 EnterpriseEncrypted Storage EngineMaster key in a KMIP server or keyfile → per-database keysWiredTiger data files, journalRotate the master key (KMIP)Enterprise only, WiredTiger only; default AES256-CBC, AES256-GCM supported on Linux
PostgreSQLNone in coreNoneNoneNoneUse 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, RedisNone built inNoneNoneNoneSQLCipher/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
-- 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.

OptionWhat it protectsCostLimit
Volume or file-system encryption (LUKS, cloud volume)Whole cluster: heap, indexes, WAL, temp files, logsAlmost nothing; hardware AESMounted means readable
pg_tde (Percona Server for PostgreSQL 17/18)Tuples, WAL, indexes; keys from keyringfile or an external KMS through a global key providerVendor distribution, not stock PostgreSQLTemp files and statistics not yet encrypted (README)
pgcrypto columnsChosen columnsQuery changes; key handling in SQL"All pgcrypto functions run inside the database server"
Application-side envelope encryptionChosen fields, key never reaches the serverSearch and constraints changeYou own the crypto code
Managed service (RDS, Cloud SQL, Azure)Volume, snapshot, backupProvider lock-in on keyProvider-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.

PlaceWhy it holds dataCovered by
WAL / redo / binlogEvery change is logged before the data fileVolume 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 exceededVolume encryption; TDE tempdb; pg_tde does not cover them yet
Server and slow-query logsStatements with literal values, and with pgcrypto, with the keylog_statement, log_min_duration_statement settings; parameter logging off
Swap and core dumpsMemory pages written to diskEncrypted swap, vm.swappiness, disable core dumps for the database user
Replicas and snapshotsFull copiesSame encryption on every node
Error messages and APM tracesValues in constraint errors and bound parametersScrub 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).

Root key (HSM, never exported)AWS KMS key / Vault seal / Oracle walletrotated rarely, access auditedKEK (key-encryption key)one per tenant or per databasewraps DEKs; rotation = rewrapDEK (data-encryption key)AES-256, per table or per recordplaintext lives only in RAMCiphertext in the databaseAES-GCM: nonce + data + tagStored together in the row / tablewrapped DEK(KMS ciphertext blob)field ciphertextnonce || data || tagkey id / version, AAD = table|column|row idRead path1 app sends the wrapped DEK to KMS Decrypt (IAM-checked, logged)2 KMS returns the plaintext DEK over TLS3 app decrypts the field with AES-GCM, tag verified4 app zeroes the DEK (or caches it for seconds)Crypto-shredding: destroy the KEK, every DEK it wraps is unreadableRotation: KMS rewraps DEKs; data is not re-encrypted
text
     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 DEK

Real 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.

PropertyData key per recordData key per tenant / tableSingle key for all data
KMS callsOne per write and read (cache to reduce)One per cache missAlmost none
Blast radius of a DEK leakOne recordOne tenant or tableEverything
Nonce-limit margin (2^32 messages per key)Never an issueCheck high-volume tablesHit eventually
Crypto-shreddingDelete the record's keyDelete the tenant's KEKImpossible without re-encrypting
Rotation costRewrap all wrapped DEKsRewrap few DEKsRe-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.

go
// 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.

ServiceWhat it offersNotes
AWS KMSKMS keys in HSMs, GenerateDataKey, Encrypt, Decrypt, key policies, grants, automatic rotation, CloudTrail auditRDS, EBS, S3 and Aurora use it for volume and snapshot keys
Google Cloud KMS, Azure Key Vault / Managed HSMSame model, different IAMAzure 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 dataKey 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 protocolMongoDB Encrypted Storage Engine and MySQL Enterprise keyring_okv speak it
PKCS#11 HSM (CloudHSM, Thales Luna)Raw hardware key operationsBacking 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).

text
     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 scenarioWhat is rewrittenDowntimeProduct feature
KEK / master keyWrapped DEKs onlyNoneMySQL 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 backgroundOnline, with I/O and CPU costSQL Server new DEK; Oracle re-key; ALTER TABLE ... ENCRYPTION in MySQL rewrites the table
Application field keyEvery encrypted column of every rowOnline if done in batchesLaravel APP_PREVIOUS_KEYS plus a re-encryption command; Tink keyset rotation
TLS certificateNothing storedNone if reloadedpg_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.

text
     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 keys

Real 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.

PracticeWhy
Back up keys separately from data, in at least two places, with access reviewsKey loss is unrecoverable
Use KMS key policies and a waiting period for deletionA mistaken ScheduleKeyDeletion can be cancelled
Test restore of an encrypted backup on a clean machine regularlyProves 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 logsSee 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."

KnobProductMeaning
ssl = on, ssl_cert_file, ssl_key_file, ssl_ca_filePostgreSQLServer certificate, key, CA for client certificates
ssl_min_protocol_version, ssl_ciphers, ssl_prefer_server_ciphersPostgreSQLFloor for TLS version; cipher list for TLS 1.2
hostssl, hostnossl, hostgssencpg_hba.confWhich connection types a line matches
require_secure_transport = ONMySQLReject non-TLS connections (error 3159)
tls_version, ssl_ca, ssl_cert, ssl_keyMySQLAllowed protocols and certificate files
net.tls.mode, net.tls.CAFileMongoDB mongodrequireTLS and certificate files
tls-port, tls-cert-file, tls-auth-clientsRedisTLS listener, certificate, client-certificate policy
Encrypt=True; TrustServerCertificate=FalseSQL Server clientsEncrypt 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.

text
     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 certificate

Replication, 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.

HopHow to encrypt itDetail
Streaming replication standby → primaryprimary_conninfo is a libpq connection string: put sslmode=verify-full sslrootcert=... sslcert=... sslkey=... in it; the primary needs a hostssl replication lineSame for CREATE SUBSCRIPTION ... CONNECTION in logical replication
MySQL replicationSOURCE_SSL=1, SOURCE_SSL_CA, SOURCE_SSL_VERIFY_SERVER_CERT=1 in CHANGE REPLICATION SOURCE TOCheck with SHOW REPLICA STATUS
MongoDB replica setnet.tls.mode: requireTLS plus cluster x.509 (clusterAuthMode)Members authenticate each other
PgBouncer client → poolerclient_tls_sslmode, client_tls_key_file, client_tls_cert_file, client_tls_ca_fileDefault disable
PgBouncer pooler → PostgreSQLserver_tls_sslmode (default prefer; use verify-full), server_tls_ca_fileTwo separate TLS sessions; see Connection Pooling
Backup tools (pg_basebackup, pgBackRest, mysqldump)Same sslmode settings in the connection string; repository encryption in the toolBackup stream and backup repository are separate concerns
Cross-region and WAN replicationTLS plus a private link or VPN; certificates with the replica's real DNS nameverify-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.

go
// 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."

text
     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
PropertyRandomisedDeterministic
Equality WHERE col = ?NoYes
GROUP BY, DISTINCT, equality joinsNoYes
Unique constraintNoYes
Frequency analysisImmuneVulnerable on low-cardinality data
Range, ORDER BY, LIKENoNo
Best forCard numbers, notes, health data, high-cardinality secretsIdentifiers 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.

WRITE: INSERT / UPDATEemailAnn@Example.comnormaliselower(trim(x))AES-256-GCMdata key, random nonceHMAC-SHA256blind-index key + fieldemail_encrandomised ciphertextrowemail_enc, email_bidxindex on email_bidxSEARCH: WHERE email = ?search term" ann@example.com "normalise + HMACsame key, same fieldWHERE email_bidx = ?B-tree equality lookupdecrypt + comparedrop false positivesWorks: equality, IN, uniqueness. Does not work: range, LIKE, ORDER BY, prefix.Leaks: which rows share a value. Truncate the HMAC (8 to 16 bytes) to blur it.
text
     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 equal

Real 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 choiceEffect
Separate blind_key per fieldEqual values in two columns do not match across columns
Include the field name in the HMAC inputSame, even with one key
Truncate the index (8 to 16 bytes)Fewer distinct values, some false positives, less leakage
Add a pepper from a KMSCracking needs the KMS
Several indexes (full, last 4 digits)Prefix-like search at the price of leaking the short values
RotationRecompute 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.

go
// 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.

text
     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
FunctionUseCaution
pgp_sym_encrypt(text, key, 'cipher-algo=aes256')Randomised, integrity-protected, saltedKey in the query; slow s2k is deliberate
pgp_pub_encrypt(text, pubkey)Write-only column: anyone can encrypt, only the private key holder can readPrivate key must be supplied to decrypt
hmac(data, key, 'sha256')Blind indexSame: key sits in the SQL
crypt(password, gen_salt('bf', 12))Password hashPrefer hashing in the application with argon2id
encrypt(), decrypt() rawLegacyThe manual discourages them
sql
-- 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 row

Tokenization 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.

TechniqueHow it worksReversible byKeeps formatTypical use
Vault tokenizationRandom token; mapping stored in a secured vault (or Vault transit tokenization)Vault lookupYes (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 domainKey holderYesLegacy columns with fixed formats, test data
Deterministic tokens (HMAC-based)Token derived from value and keyNobody (one-way)OptionalJoins across systems without sharing values
Randomised encryptionStandard AEADKey holderNoGeneral 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."

PieceWhereNote
casts() with 'email' => 'encrypted'ModelSame key for every row: tenant keys need a custom cast
email_bidx column and saving hookMigration, modelHMAC with its own key from config('services.blind_index.key')
whereEmailIs() scopeModelNormalises, computes HMAC, filters on the index
crypto:reencrypt commandArtisanRaw DB::table update because Eloquent skips unchanged plaintext
APP_PREVIOUS_KEYS.envRemove an old key only after re-encryption is verified
php
<?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
<?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
<?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).

AspectCSFLEQueryable Encryption
AlgorithmsDeterministic or randomised AEADRandomised with encrypted indexes
Query typesEquality (deterministic only)Equality, range, prefix, suffix, substring
LeakageEquality and frequency for deterministic fieldsDesigned to hide frequency; documented leakage profile
CostLowExtra metadata, larger payloads, more driver work
Server seesCiphertextCiphertext 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.

ModeEqualityRange, LIKE, sortJoins and GROUP BYTrust assumption
DeterministicYesNoYesServer never sees plaintext
RandomisedNoNoNoServer never sees plaintext
Randomised + secure enclaveYesYesYesEnclave (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.

ConcernConsequence
IndexesOnly on blind indexes or deterministic ciphertext
ConstraintsUNIQUE on the index column; CHECK cannot see plaintext
MigrationsChanging the type or format means decrypt, transform, encrypt in the application
Backups and replicasSafe without extra work, until you restore without the key
ReportingNeeds 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.

text
     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
TechnologyProtectsGranularityNotes
AMD SEV, SEV-SNPWhole VM memory; SNP adds integrity against replay and remappingVMLift-and-shift: run PostgreSQL unchanged in a Confidential VM
Intel TDXTrust domain (VM) memoryVMSimilar model on Intel; attestation from the platform
Intel SGXSelected code and data in an enclaveProcess or enclaveRequires 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 offeringsThe above as a VM type or Nitro EnclavesVM or enclaveCheck 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.

ClassOperationsExamplesPractical use
PHE (partially homomorphic)One operation, unlimited times: addition (Paillier) or multiplication (RSA textbook, ElGamal)Paillier sum of encrypted salariesEncrypted SUM, voting tallies, ad measurement
SHE / levelled HE (somewhat)Both addition and multiplication, but limited circuit depth before noise grows too largeBFV, BGV, CKKS (approximate numbers)Small statistics, linear models, private set operations
FHE (fully)Arbitrary computation, using bootstrapping to refresh noiseTFHE, 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.

text
     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 not

Hashing, 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.

NeedRight toolWrong tool
Store a user passwordargon2id or bcrypt with per-user saltAES, SHA-256, MD5, one global salt
Store an API token you must show againEncrypt (AEAD)Hash (you cannot show it)
Store an API token you only verifyHash with HMAC or SHA-256 (high-entropy secret)Encrypt
Search an emailBlind index (HMAC)Plain SHA-256
Verify a file or message was not alteredHMAC or AEAD tagBare 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.

ProductFeatureWhat it doesLimits
SQL Server, Azure SQLDynamic Data Masking (MASKED WITH (FUNCTION = 'partial(...)'), UNMASK permission)Masks results for users without UNMASKInference through WHERE is possible; not a security boundary on its own
MySQL EnterpriseData masking components and functionsMasks values in queries and generates masked dataEnterprise edition
PostgreSQLpostgresql_anonymizer extension (dynamic and static masking), or views with CASE per role, or RLSMasks for roles, or rewrites a copyExtension install; views must be the only access path
OracleData RedactionRedacts at query timeLicensed option
Application layerSerializer or resource that hides fieldsPer-API maskingEasy to forget in one endpoint
Non-production copiesStatic masking or synthetic dataReal values never leave productionCovered 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.

ProductBackup encryption
PostgreSQLpg_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
MySQLPercona XtraBackup --encrypt; MySQL Enterprise Backup encryption; binlog encryption (binlog_encryption=ON)
SQL ServerTDE-encrypted databases give encrypted backups; BACKUP ... WITH ENCRYPTION (ALGORITHM = AES_256, SERVER CERTIFICATE = ...)
OracleRMAN backup encryption (transparent, password or dual mode)
MongoDBEncrypted storage engine data; mongodump output encrypted by the pipeline; Atlas encrypts snapshots
RDS / AuroraSnapshots and backups of an encrypted instance are encrypted with the same KMS key
SQLite, RedisEncrypt 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 sourceWhat happensHow to measure and reduce
AES in the CPU (AES-NI on x86, ARMv8 crypto extensions)Hardware rounds make block encryption cheapCheck the CPU flag (grep aes /proc/cpuinfo); Go's crypto/aes and OpenSSL use the instructions when present
TDE page encryptionEncrypt on write to disk, decrypt on read into the buffer pool; hot data in cache is plaintextRun pgbench or sysbench before and after, compare p95 latency and CPU
KMS round tripsNetwork call per unwrap (milliseconds)Cache unwrapped DEKs in memory for seconds; one DEK per tenant
Larger rowsCiphertext is longer (nonce + tag, base64 if text)TEXT or bytea; mind row size and TOAST
Lost indexesEncrypted columns cannot use range indexesBlind index for equality; separate plain derived columns for ranges
TLSHandshake per connection, small per-byte costPooling and reuse; session resumption; TLS 1.3 saves a round trip
Application encryptionCPU in the application tierScale 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.

FrameworkWhat the text asks forLayers that answer it
GDPR Art. 32"the pseudonymisation and encryption of personal data" among measures appropriate to the riskTDE 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 securityTDE or volume, field encryption for ePHI, TLS verify-full; Addressable means document the decision if you do not implement it
PCI DSS v4.xProtect 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 controlsVolume or TDE, TLS, KMS audit logs
Data residency and sovereigntyControl over who can access data and whereClient-side keys held in-country (HYOK), confidential computing with attestation, regional KMS
Compliance questionHonest 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 ​

ProductEncryption at restColumn / fieldIn transitClient-side / in useKey management
PostgreSQLNone in core; volume encryption; pg_tde in Percona Server for PostgreSQLpgcrypto (server-side), application-sideSSL/TLS (sslmode, hostssl), GSSAPI encryption, mTLS with clientcertClient-side by design; run in a Confidential VMYour own; KMS through pg_tde key providers
MySQL 8.4 / InnoDBTablespace encryption with keyring master key; redo, undo, binlog encryption optionsAES_ENCRYPT() (server-side, key in SQL), application-sideTLS (require_secure_transport, REQUIRE X509)Application-side; Confidential VMKeyring component: file (all editions), encrypted file, KMIP, AWS, others (Enterprise)
SQL ServerTDE (AES), backup encryptionAlways Encrypted (client-side), cell-level ENCRYPTBYKEYTLS (Encrypt, TrustServerCertificate)Always Encrypted with secure enclaves (VBS)Certificates, EKM, Azure Key Vault, HSM
OracleTDE tablespace and column encryption, RMAN backupsTDE column encryption, DBMS_CRYPTONative network encryption and TLSData Redaction (display), Database VaultKeystore: software wallet, HSM, Oracle Key Vault; ADMINISTER KEY MANAGEMENT
MongoDBEncrypted Storage Engine (Enterprise, WiredTiger), Atlas defaultCSFLE (field), Queryable EncryptionTLS (requireTLS), x.509CSFLE and QE are client-sideKMIP, AWS/Azure/GCP KMS
SQLiteNone in core; SQLCipher or SEE (third-party)Application-sideNot applicable (embedded)Not applicableApplication
CockroachDBEnterprise encryption at rest (verify in its docs), volumeApplication-sideTLS required by default in secure mode (verify)Application-sideStore key files or KMS
RedisNone in open source; managed services at the volume levelApplication-side (values are opaque bytes)TLS (tls-port), mTLSNot applicableService or application
AWS RDS / AuroraVolume and snapshot encryption with KMS (AES-256)Same as the enginePer-engine TLS; the in-region replication link is encryptedApplication-sideAWS KMS key per instance

Defaults that bite ​

DefaultEngineConsequence
sslmode=preferlibpq, Laravel pgsqlFalls back to plaintext silently; not verified
No TLS configuredPostgreSQL, MySQL, Redis out of the boxPlaintext on the wire until you enable it
innodb_redo_log_encrypt offMySQLRedo log holds plaintext even if tablespaces are encrypted
TDE offSQL Server, OracleNothing is encrypted until enabled
ENCRYPTION default offMySQL tablesNeeds ENCRYPTION='Y' or schema default DEFAULT ENCRYPTION='Y'
pgp_sym_encrypt default cipherpgcryptoDefaults to AES-128 unless cipher-algo=aes256
local keyring fileMySQL component_keyring_fileMaster key sits on the same host as the data
Rotation offKMS keysEnable automatic rotation or plan manual rotation

Mechanics ​

Every knob in one table Must-know ​

SettingProductMeaning
ssl, ssl_cert_file, ssl_key_file, ssl_ca_file, ssl_crl_filePostgreSQL serverTurn TLS on; trust anchors; revocation
ssl_min_protocol_version, ssl_max_protocol_version, ssl_ciphersPostgreSQL serverProtocol and cipher policy; default minimum TLSv1.2
sslmode, sslrootcert, sslcert, sslkey, sslcrllibpq clientVerification level and certificates
clientcert=verify-ca / verify-fullpg_hba.confRequire and verify client certificates
password_encryption = scram-sha-256PostgreSQLHash format for role passwords
CREATE EXTENSION pgcryptoPostgreSQLHashing, HMAC, PGP functions
require_secure_transport, tls_version, ssl_ca, ssl_cert, ssl_keyMySQLTLS enforcement and files
ENCRYPTION='Y', default_table_encryption, innodb_redo_log_encrypt, innodb_undo_log_encrypt, binlog_encryptionMySQLWhat is encrypted at rest
ALTER INSTANCE ROTATE INNODB MASTER KEY, ALTER INSTANCE RELOAD TLSMySQLKey and certificate rotation
CREATE DATABASE ENCRYPTION KEY, ALTER DATABASE ... SET ENCRYPTION ON, sys.dm_database_encryption_keysSQL ServerTDE
ADMINISTER KEY MANAGEMENT, ENCRYPTION USING 'AES256'OracleKeystore and encrypted tablespaces
security.enableEncryption, encryptionCipherMode, encryptionKeyFile, kmip.*MongoDB mongodEncrypted Storage Engine
client_tls_sslmode, server_tls_sslmode, *_tls_ca_filePgBouncerPooler TLS on both legs
APP_KEY, APP_PREVIOUS_KEYS, cipher in config/app.phpLaravelEncrypter key, rotation, AES-256-CBC or AES-256-GCM family

Error codes and messages you will see Important ​

Message or classFromMeaningFix
SSL error: certificate verify failedlibpqChain not trusted by sslrootcertInstall the right CA; do not drop to require
server certificate for "db-lab" ... does not match host name "172.18.0.2"libpq verify-fullConnected by a name missing from the certificate SANUse the DNS name in the certificate, or reissue
server does not support SSL, but SSL was requiredlibpqServer TLS off, client demanded itEnable ssl = on or fix the host
pg_hba.conf rejects connection for host ..., no encryptionPostgreSQLA hostssl line exists and the client used plaintextSet sslmode=require or stronger
MySQL 3159 ER_SECURE_TRANSPORT_REQUIREDMySQLrequire_secure_transport=ON and the client used plaintextConnect with TLS
Wrong key or corrupt datapgp_sym_decryptWrong key or damaged ciphertextCheck key version; restore from backup
Cannot find server certificate with thumbprint ...SQL Server restoreTDE certificate missing on the new serverRestore certificate and private key first
Illuminate\Contracts\Encryption\DecryptException ("The MAC is invalid.")LaravelWrong APP_KEY, tampered or truncated ciphertextAdd the old key to APP_PREVIOUS_KEYS
cipher: message authentication failedGo crypto/cipherAEAD tag mismatch: wrong key, wrong AAD, modified dataCheck key id, AAD (row identity), column truncation
InvalidCiphertextException, KMSInvalidStateException, DisabledException, AccessDeniedExceptionAWS KMSBad blob or wrong key; key pending deletion; key disabled; IAM deniesFix key id and policy; cancel deletion in time

How a read works through each layer ​

text
     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 trail

Solving the classic problems ​

A stolen backup or snapshot ​

SolutionHowAdvantageCost or limit
Encrypt backups with a KMS key and keep the key elsewherepgBackRest repo encryption, BACKUP ... WITH ENCRYPTION, RMANStolen file is noiseKey custody, restore drills
Field-level encryption of the sensitive columnsLaravel casts, Always Encrypted, CSFLEEven a plaintext dump has no secretsSearch and reporting limits
Short retention plus crypto-shredding by tenantKEK per tenant, destroy to deleteMeets erasure in backupsOperational maturity

A DBA or a cloud operator must not read the data ​

SolutionHowAdvantageCost or limit
Client-side keysLaravel encrypted, Always Encrypted, CSFLE, tink-goServer never has plaintextApplication becomes the trust anchor
Confidential VM with attestationSEV-SNP or TDX plus key release after attestationUnchanged SQL and indexesTrust in the CPU vendor and in your image
Separation of duties and auditDifferent people for DB and key admin, pgAuditCheap, proceduralNot cryptographic
NeedSolutionLimit
Equality (email, national ID)Blind index (HMAC) or deterministic encryptionLeaks equality
Prefix searchSeveral truncated blind indexes (first 3 letters)Leaks the short values; limited
Range, sortEnclave (Always Encrypted), Queryable Encryption, or a plaintext coarse bucket (age band)Hardware trust, or deliberate leakage
Full textDo not encrypt; move to a separate indexed store with its own protectionPolicy decision
go
// 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 ​

StepActionSafe to stop here?
1Generate the new key, set APP_KEY new and APP_PREVIOUS_KEYS oldYes (reads work, new writes use new key)
2Run crypto:reencrypt in chunksYes (idempotent)
3Query for rows still failing under the new key onlyYes
4Remove the old keyNo: irreversible without a backup of the old key
php
<?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 ​

KeyImmediate actionFollow-up
DEK of one record or tenantRe-encrypt that data under a new DEKReview who could call Decrypt
KEKCreate a new version, rewrap all DEKs, disable the old versionAudit KMS logs for the exposure window
APP_KEYRotate with APP_PREVIOUS_KEYS, re-encrypt, invalidate sessions and signed URLsCookies and other encrypted payloads also use this key
Blind-index keyRecompute every indexEquality leaks for the period are permanent
TLS private keyReissue and reload certificates, revokessl_crl_file, short-lived certificates

Choosing ​

SituationRecommended layerExtra techniqueReason
Any production databaseVolume or cloud-managed encryption + TLS verify-fullEncrypted backups, key in KMSBaseline everyone expects
Auditor asks "encryption at rest" on SQL Server, Oracle, MySQLTDEKeep certificate backups, test restoreSatisfies the checkbox, cheap
PostgreSQL with that requirementVolume encryption (or pg_tde on Percona)WAL and temp-file coverage checkCore has no TDE
National ID, card number, health notesApplication-side randomised encryptionBlind index for lookups; tokenization for cardsDBA and backup also covered
Multi-tenant SaaS with enterprise customersKEK per tenant, optionally customer-managed (BYOK)Crypto-shredding on offboardingPer-tenant erasure and trust
Host or cloud operator is the adversaryConfidential VM with attestationClient-side keys for the crown jewelsProtects data in use
Need range and LIKE on encrypted dataSQL Server enclaves or MongoDB Queryable EncryptionAccept the leakage profileServer-side query power
Private sums over a few valuesPHE (Paillier) or CKKSDo it in a small serviceFHE for general SQL is not practical
Passwordsargon2id (or bcrypt)Pepper, rate limitsNever reversible
Non-production dataMasked or synthetic copyNo production dumpsRemoves 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 ​

text
     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 key

Service-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× ​

LoadWhat changesExample
1×Managed encryption, TLS, a handful of encrypted fields, one KMS keyStartup 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 jobsCache 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 tierEnterprise SaaS with BYOK and crypto-shredding on contract end
AnyKey loss, audit and restore drills never become optionalQuarterly 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)

sh
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
text
 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.com

Experiment 2: wrong key and tampering

sql
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 sees

Experiment 3: the key is visible to the server

sql
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 superuser

Experiment 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.

sh
#!/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
text
--- 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

sh
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 destroyed

Experiment 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
<?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 ​

BeliefReality
"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 ​

TopicWhat to remember
Start from the attackerDisk thief, backup leak, sniffer, DBA, memory dump, cloud operator: one layer each
Volume and TDEProtect media, not logins; cheap; transparent
PostgreSQLNo TDE in core; use volume encryption or pg_tde on Percona; pgcrypto passes the key through the server
Envelope encryptionDEK encrypts data, KEK wraps DEK, KMS/HSM holds the KEK; rotate by rewrap
GCMFresh nonce per message, at most 2^32 random-nonce messages per key; bind AAD to the row
TLSverify-full (or MySQL VERIFY_IDENTITY), minimum TLS 1.2, cover replication and poolers
mTLSclientcert=verify-full in pg_hba.conf; REQUIRE X509 in MySQL
SearchableBlind index = HMAC with its own key; equality only; truncate to blur
DeterministicEquality works, frequency leaks; avoid on low cardinality
Client-sideLaravel encrypted, Always Encrypted, CSFLE, Queryable Encryption: the server never has the key
In useConfidential VM (SEV-SNP, TDX) with attestation; SGX for enclaves; HE only for small jobs
Passwordsargon2id or bcrypt, never encryption
MaskingDisplay rule, not encryption
BackupsEncrypt separately; test restore with documented keys only
Key lossData loss; crypto-shredding is deletion on purpose
ComplianceGDPR Art. 32 names encryption and pseudonymisation; HIPAA encryption is Addressable; map every rule to a layer

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
AAD (additional authenticated data)Data bound into an AEAD tag but not encrypted, such as table, column and row id
AEADAuthenticated encryption with associated data (AES-GCM, ChaCha20-Poly1305)
AES-GCMCounter-mode AES with a Galois authentication tag; NIST SP 800-38D
AES-NICPU instructions that accelerate AES
AttestationCryptographic proof of what code and hardware a VM or enclave is running
Blind indexKeyed HMAC of a value stored for equality search
BYOK / HYOKBring your own key / hold your own key (key stays outside the provider)
CEK / CMKColumn encryption key / column master key in SQL Server Always Encrypted
Confidential computingHardware-protected memory for data in use (SEV-SNP, TDX, SGX)
Crypto-shreddingDeleting data by destroying its key
CryptoperiodTime span a key is authorised for use (NIST SP 800-57)
CSFLEMongoDB Client-Side Field Level Encryption
Deterministic encryptionSame plaintext always gives the same ciphertext
DEKData-encryption key
Envelope encryptionEncrypting data with a DEK and wrapping the DEK with a KEK
FHE / SHE / PHEFully, somewhat and partially homomorphic encryption
Format-preserving encryption (FPE)Encryption whose output has the same format as the input (FF1, FF3-1)
HMACHash-based message authentication code, a keyed hash
HSMHardware security module holding keys in tamper-resistant hardware
KEKKey-encryption key that wraps DEKs
KMSKey management service (AWS KMS, Cloud KMS, Azure Key Vault)
mTLSMutual TLS: both sides present certificates
Nonce / IVPer-message value that must not repeat under the same key
Queryable EncryptionMongoDB scheme supporting queries over randomly encrypted fields
Randomised encryptionSame plaintext gives different ciphertext each time
sslmodelibpq setting for TLS usage and verification
TDETransparent Data Encryption: engine-level file encryption
TokenizationReplacing a value with a random token mapped in a vault
Wrapped keyA key encrypted by another key

References ​

Built by Morteza Negahi