How to Encrypt Data at Rest in PostgreSQL
Protect sensitive columns with application-side or pgcrypto encryption, manage keys separately, and understand what encryption breaks.
On this page
Introduction
Encryption at rest protects data from someone who obtains the storage: a stolen disk, a snapshot, a backup file. Full-disk encryption covers the physical theft case, but it does nothing once the database is running, because the decryption key is available to the database process. Column-level encryption adds a second layer that protects specific fields even from a database operator or a backup that escapes its environment. This article covers the layers, how to encrypt columns with pgcrypto or in the application, how key management fits, and the query limitations that encryption imposes.
Why Encryption at Rest
Full-disk and volume encryption protect against the loss of the physical medium, which is a real but narrow threat. They do not protect against a compromised database process that reads the decrypted pages, nor against a backup copied out of the environment, because the key travels with the data in many setups. Application-level or column-level encryption narrows the exposure: only the holders of a separate key can read the sensitive fields, even if they can read everything else.
Encryption is a control with costs, so apply it where the data sensitivity justifies it: credentials, tokens, government identifiers, financial details. Encrypting everything increases key-management burden and query complexity for little benefit if most columns are already non-sensitive.
Encryption Layers
There are three practical layers. Storage encryption protects the medium. Database-level encryption, such as transparent data encryption in some engines, protects data files but is transparent to queries, so anyone with database access sees plaintext. Column-level encryption protects individual fields and requires a key that the database or the application holds separately; this is what gives a second layer.
Column-level encryption can be done in the application before the value is sent, or in the database with a function such as pgcrypto. Application-side encryption keeps the plaintext and the key out of the database entirely, which is stronger, at the cost of losing database-side search and indexing on those fields. Database-side is easier to adopt and keeps the key with the database, which is weaker if the database is the thing compromised.
Encrypting Columns with pgcrypto
pgcrypto provides symmetric encryption functions. Encrypt with pgp_sym_encrypt using a key supplied per statement, and decrypt with pgp_sym_decrypt. Store the ciphertext as bytea. Authenticated encryption modes detect tampering, so a modified ciphertext fails to decrypt rather than returning garbage. Never use a mode without authentication for data you will trust after reading it back.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Encrypt on insert; the key is supplied by the application, not stored here.
INSERT INTO users (id, email, ssn_encrypted)
VALUES (
1,
'[email protected]',
pgp_sym_encrypt('123-45-6789', $k$...application key...$k$)
);
-- Decrypt on read; a wrong key or tampered ciphertext raises an error.
SELECT id, email,
pgp_sym_decrypt(ssn_encrypted, $k$...application key...$k$) AS ssn
FROM users
WHERE id = 1;
-- Store the column as bytea; never as text (base64 would double the size).
ALTER TABLE users ALTER COLUMN ssn_encrypted TYPE bytea USING ssn_encrypted::bytea;
Key Management
The key is the whole security property: if it sits in the same database or the same repository as the data, the encryption is theatre. Keep the key in a key management service or a secret manager, inject it into the application at runtime, and never log it. Rotate it on a schedule, and keep decryption of old data working by recording which key version encrypted each value.
For multiple rows, generate a per-row data key and wrap it with a master key, so a single leaked data key exposes only one row. This is envelope encryption applied to the row. It adds a wrapped-key column and a KMS unwrap per read, which is a real cost; apply it where one compromised row should not reveal others.
What Encryption Breaks
Encrypted columns cannot be searched with equality, range or LIKE, because the ciphertext is not ordered or comparable. Deterministic encryption lets you search on equality by reusing the same ciphertext for the same plaintext, but it leaks equality: an attacker can see which rows share a value. This is acceptable for a lookup column such as a token that must be matched exactly, and unacceptable for a field whose distinct values are sensitive.
Indexing an encrypted column requires a deterministic scheme or a blind index: store a keyed hash of the value in a separate column and index that. The blind index supports equality only and must be built with a key, or it becomes a dictionary attack target. Accept that searching encrypted fields is limited, and design the schema so the fields you need to query are not the ones you encrypt.
-- Blind index: a keyed hash column for equality lookups on a token.
ALTER TABLE sessions ADD COLUMN token_lookup bytea;
-- Write both the encrypted value and its keyed hash on insert.
UPDATE sessions
SET token_encrypted = pgp_sym_encrypt($1, $k$...app key...$k$),
token_lookup = hmac($1, $k$...index key...$k$, 'sha256')
WHERE id = $2;
CREATE INDEX idx_sessions_token_lookup ON sessions (token_lookup);
-- Equality lookup uses the index; range and LIKE are impossible.
SELECT * FROM sessions
WHERE token_lookup = hmac($1, $k$...index key...$k$, 'sha256');
Rotating Encrypted Data
Rotating a key that encrypts a column used by millions of rows is a migration: decrypt with the old key and re-encrypt with the new one, in batches, without downtime and without leaving a window where a row cannot be read. Track a key version per row so you can migrate incrementally and know when the old version is unused.
A safer pattern is re-wrapping rather than re-encrypting: encrypt each row with a data key, wrap that data key with the master key, and rotate only the wrapped keys. That is the envelope approach from before, and it makes rotation cheap because only the small wrapped keys change. Design for it before you accumulate millions of rows, because retrofitting it later is a large project.
Conclusion
Encryption at rest has layers, and only column-level encryption gives protection beyond physical media. Encrypt sensitive fields with pgcrypto or in the application, keep the key in a separate key service with rotation and versioning, and use envelope encryption where a single leaked row should not expose others. Accept the query limitations: encrypted columns cannot be searched directly, and deterministic schemes leak equality. Build a blind index where you must query, and plan rotation as a migration with key versions. Test that a wrong key fails to decrypt and that a tampered ciphertext is rejected rather than returning garbage. Encrypt what is sensitive, and be honest about what each layer does and does not protect.
Sources: PostgreSQL: pgcrypto, PostgreSQL: encryption options, OWASP: Cryptographic Storage Cheat Sheet.
FAQ
- If full-disk encryption is on, do I still need column encryption?
- Yes, for different threats. Disk encryption protects the stolen medium but not a running database process or a backup copied out with its key. Column-level encryption with a key held separately protects the fields even from someone who can read the rest of the database.
- Why can I not use a LIKE query on an encrypted column?
- Encryption destroys ordering and comparability, so the database cannot match a pattern against ciphertext. Only a deterministic scheme supports equality lookups, and even that leaks which rows share a value. Use a blind index on a keyed hash for equality if you must query an encrypted field.
Report a problem with this articleOpens a pre-filled issue on GitHub.