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.
Disk encryption protects a stolen drive and does nothing about a stolen SQL dump. Encrypting a field in your code does.
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')));123-45-6789The 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.