How-To Guide

How to Implement Field-Level Encryption

Encrypt sensitive columns individually with per-field keys and authenticated encryption, keeping plaintext out of databases, backups and logs.

On this page

  1. Introduction
  2. What Field-Level Encryption Protects Against
  3. Per-Field Keys and Authenticated Encryption
  4. Searchable Fields via Blind Indexes
  5. Keeping Plaintext Out of Logs and Telemetry
  6. Queries, Sorting and Joins
  7. Migration and Key Rotation
  8. Common Pitfalls and Conclusion

Introduction

Encrypting a database at rest protects against a stolen disk but not against a compromised application, a misconfigured backup, or a query that exposes the wrong column. Field-level encryption addresses the harder threat: the sensitive value is encrypted before it reaches the database, so the plaintext is never stored there at all. A leaked backup, a database dump, or a curious operator sees ciphertext. The cost is that encrypted fields cannot be searched or joined in the normal way, so the design must decide which fields to encrypt and how to support the queries those fields need.

What Field-Level Encryption Protects Against

Disk encryption and tablespace encryption protect data when the storage is compromised. They do not protect against an application that reads too much, a backup exported to an unencrypted bucket, a replica granted to a third party, or a support engineer with broad read access. Field-level encryption removes the plaintext from the database entirely, so all of those exposures see only ciphertext.

The trade-off is real: an encrypted column is opaque to the database. You cannot index it for equality or range queries, sort it, or join on it, unless you store a deterministic token separately. Choose fields where the sensitivity justifies the loss of queryability: government identifiers, payment details, health data, recovery secrets.

# threat coverage
                     disk enc   table enc   field enc
stolen disk          yes        yes         yes
leaked backup        maybe      maybe       yes
over-broad app read  no         no          yes
replica to 3rd party no         no          yes
# field encryption removes plaintext from the DB => covers app/backup leaks

Per-Field Keys and Authenticated Encryption

Encrypt each field value with an authenticated cipher such as AES-GCM or ChaCha20-Poly1305, and bind the ciphertext to its context with additional authenticated data. The AAD should include the field name, the record id and a version, so a ciphertext moved to a different field or record fails to decrypt rather than silently yielding a wrong value.

Use a key per field class rather than one key for everything, so a compromise of the payment key does not expose health data. The keys live in a KMS or secret store and the data key for each field is fetched by reference, never hard-coded. Rotation means re-encrypting the affected column with a new key, which is expensive, so design for it from the start.

import { createCipheriv, randomBytes } from 'node:crypto';

export function encryptField(field: string, recordId: string, plaintext: string, key: Buffer) {
  const iv = randomBytes(12);
  const cipher = createCipheriv('aes-256-gcm', key, iv);
  cipher.setAAD(Buffer.from(`${field}:${recordId}:v1`));   // bind context
  const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
  return {
    v: 1,                       // algorithm/key version for rotation
    iv: iv.toString('base64'),
    ct: ct.toString('base64'),
    tag: cipher.getAuthTag().toString('base64'),
  };
}

Searchable Fields via Blind Indexes

If you must query an encrypted field for equality, store a separate blind index: a deterministic, keyed hash of the plaintext, computed with a key held outside the database. The index is deterministic so equality queries work, and keyed so an attacker without the key cannot build a rainbow table. It leaks equality and frequency patterns, so use it only where necessary.

The blind index column is not the plaintext; it is a token. Index it normally and query by hashing the search value with the same key. Accept the leakage: an attacker with database access can learn which records share a value, which is usually acceptable for high-entropy values such as identifiers and unacceptable for low-entropy ones such as a boolean flag.

import { createHmac } from 'node:crypto';

// Blind index: deterministic, keyed, stored in a separate column.
export function blindIndex(value: string, indexKey: Buffer): string {
  return createHmac('sha256', indexKey).update(value.toLowerCase()).digest('base64');
}

// Store: email_index = blindIndex(email, k) alongside email_ct (ciphertext).
// Query: WHERE email_index = blindIndex(searchEmail, k) -- equality only.
// Leaks: which rows share a value; do NOT use for low-entropy values.

Keeping Plaintext Out of Logs and Telemetry

Field-level encryption is undermined if the plaintext is logged, traced or sent to an error reporter. After decrypting a field for use, keep it out of log lines, span attributes, and exception payloads. Configure the framework to redact the specific fields, and treat any logging of a decrypted value as a bug.

The decryption boundary should be as narrow as possible: decrypt just before use and discard immediately, never place decrypted values in a long-lived object that could be serialised into a log. A request-scoped decryption cache is fine if it is cleared at the end of the request; a global cache of decrypted values is not.

// Redact decrypted fields from logs by name, not by hoping.
const SENSITIVE = new Set(['ssn', 'cardNumber', 'recoveryCode']);

function toLoggable(record: Record<string, unknown>) {
  return Object.fromEntries(
    Object.entries(record).map(([k, v]) => [k, SENSITIVE.has(k) ? '[redacted]' : v]),
  );
}
// decrypt -> use -> discard; never assign a decrypted field to a logged object

Queries, Sorting and Joins

Range queries, sorting and joins on encrypted fields are not possible without leaking order. If you need sorting by an encrypted field, either accept leaking order through an order-preserving scheme (which weakens security) or don’t encrypt that field and rely on access controls instead. Decide per field: encrypt what needs confidentiality more than queryability.

Joins on an encrypted foreign key need a blind index of that key on both sides, or a surrogate key plus a separate mapping. In practice, encrypt the sensitive payload and keep an opaque surrogate id in the clear for relationships, so joins use the id and the secret stays encrypted. This separation is what keeps the schema usable.

-- Keep an opaque surrogate for relationships; encrypt only the payload.
CREATE TABLE customers (
  id            uuid PRIMARY KEY,          -- clear surrogate, used for joins
  ssn_ct        jsonb NOT NULL,            -- encrypted payload + iv + tag + version
  ssn_index     text NOT NULL,             -- blind index for equality lookups
  created_at    timestamptz NOT NULL DEFAULT now()
);
-- joins use id; ssn stays encrypted; equality queries use ssn_index

Migration and Key Rotation

Encrypting an existing plaintext column is a migration: add the ciphertext column, backfill by reading each plaintext value, encrypting it, writing it, and clearing the plaintext, then flip reads to the new column and drop the old one. Do it in batches with the ability to resume, and verify row counts and decryption on a sample before dropping the plaintext.

Rotation is harder than for envelope encryption because each field value must be re-encrypted. Store a version with each ciphertext and decrypt with the version’s key, so you can rotate incrementally: write new values with the new version, and a background job re-encrypts old rows. Never remove a key version until no ciphertext references it.

# column migration to field encryption
1. add ssn_ct (jsonb) and ssn_index (text)
2. backfill in batches: read ssn, encrypt -> ssn_ct, write ssn_index
3. dual-read: prefer ssn_ct, fall back to ssn during backfill
4. verify sample decrypts + row counts match
5. stop writing plaintext ssn; flip reads to ssn_ct
6. drop the plaintext column
# rotation: version each ciphertext; re-encrypt lazily or in background

Common Pitfalls and Conclusion

Do not encrypt with a single key for all fields, or the blast radius is the whole dataset. Do not use an unauthenticated cipher mode, which allows silent tampering. Do not log decrypted values. Do not use a blind index on a low-entropy field, where frequency analysis breaks it. Do not forget the AAD binding, which prevents moving ciphertext between records. And do not encrypt fields you need to sort or range-query without accepting the leakage.

Field-level encryption protects the sensitive value from the database itself, covering backup leaks, over-broad reads and compromised replicas that disk encryption cannot. Encrypt per field class with authenticated encryption and bound AAD, support equality with keyed blind indexes where needed, keep plaintext out of logs, use clear surrogates for relationships, and version ciphertexts for rotation. The result is that a database leak is a pile of ciphertext.

Sources: OWASP: Cryptographic Storage Cheat Sheet, NIST SP 800-38D: GCM mode, PostgreSQL: Encryption options.

FAQ

Can I search an encrypted field?
Not directly; an encrypted column is opaque to the database. For equality, store a separate keyed blind index and query that. Range queries and sorting would leak order, so avoid encrypting fields you need to sort unless you accept the weaker security.
How is this different from tablespace encryption?
Tablespace encryption protects the data on disk but the database and any application with read access see plaintext. Field-level encryption encrypts values before they reach the database, so backups, replicas and over-broad reads also see only ciphertext.

Related Examples