Skip to content
jshacks.dev
Security

Encrypt sensitive fields in a database

Encrypt a sensitive column such as a national ID with AES-256-GCM before saving, and decrypt it only when you need the value.

1 min read
Summarize in AI

Disk encryption protects a stolen drive and does nothing about a stolen SQL dump. Encrypting a field in your code does.

field.jsJavaScript
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';

const KEY = Buffer.from(process.env.FIELD_KEY, 'base64'); // 32 bytes

export function encryptField(plain) {
  const iv = randomBytes(12);
  const cipher = createCipheriv('aes-256-gcm', KEY, iv);
  const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
  return Buffer.concat([iv, cipher.getAuthTag(), data]).toString('base64');
}

export function decryptField(stored) {
  const raw = Buffer.from(stored, 'base64');
  const decipher = createDecipheriv('aes-256-gcm', KEY, raw.subarray(0, 12));
  decipher.setAuthTag(raw.subarray(12, 28));
  return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8');
}

console.log(decryptField(encryptField('123-45-6789')));
Text
123-45-6789

The stored string holds a 12-byte IV, a 16-byte authentication tag and the ciphertext, so one column is enough. A changed byte makes final() throw, which tells you the data was tampered with. See crypto.createCipheriv.

You cannot search or sort an encrypted column, so keep a separate keyed hash of the value if you must look it up. Keep the key in a secrets manager and plan how to rotate it by storing a key version beside each value.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.