






















Your users table has a column called stripe_api_key. It stores the API key in plaintext. You tell yourself it is fine because Postgres is encrypted at rest, the database is firewalled, and you trust your team.
Then a developer runs pg_dump to a local machine for debugging and the backup sits in a downloads folder for three weeks. Or a SQL injection bypasses the ORM for three hours before the WAF catches it. Or an S3 bucket with nightly backups gets misconfigured and someone scrapes 40GB of database dumps.
The encryption at rest your cloud provider offers protects the volume. It does not protect against anyone who has a database connection, a backup file, or a SELECT statement. Application-layer encryption means the database never sees the plaintext. Not the column values, not the WAL, not the replicas.
This post covers the exact encryption utility you need: AES-256-GCM for authenticated encryption, PBKDF2 for key derivation, a key management table for rotation, and the testing patterns that prove the code is correct. No external dependencies beyond node:crypto.
AES-256-GCM is the only mode you should consider for application-level encryption in 2026. Here is why.
AES-GCM is an authenticated encryption mode. It produces a ciphertext and an authentication tag, which is a MAC over the ciphertext plus optional associated data. When you decrypt, GCM verifies the tag before releasing the plaintext. If the ciphertext is tampered with, truncated, or corrupted, the tag check fails and the decryption returns an error. No garbage plaintext, no buffer overflow, no padding oracle attack.
AES-CBC (the mode most Node.js tutorials from 2018 recommend) does not authenticate. An attacker can flip bits in the ciphertext and the decryption produces a corrupted but valid-looking plaintext. You need a separate HMAC to detect tampering, and most developers forget to add it, or compute the HMAC over the wrong fields, or reuse the encryption key for the MAC. AES-GCM eliminates that entire class of mistakes by design.
AES-256-GCM requires a 256-bit key (32 bytes) and a 96-bit nonce (12 bytes). The nonce must be unique per key. Reusing a nonce with the same key leaks the GHASH authentication key and destroys security. In practice, you generate a random nonce for every encryption and store it alongside the ciphertext.
Here is the core utility. It is about 40 lines, takes a key and plaintext, returns a URL-safe string that bundles the nonce, ciphertext, and tag.
import { randomBytes, createCipheriv, createDecipheriv, pbkdf2Sync } from 'node:crypto';
const ALGORITHM = 'aes-256-gcm';
const KEY_LENGTH = 32; // 256 bits
const NONCE_LENGTH = 12; // 96 bits
const TAG_LENGTH = 16; // 128 bits
const SALT_LENGTH = 32;
export function encrypt(plaintext: string, key: Buffer): string {
const nonce = randomBytes(NONCE_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, nonce);
const encrypted = Buffer.concat([
cipher.update(plaintext, 'utf-8'),
cipher.final(),
]);
const tag = cipher.getAuthTag();
// Bundle: nonce + ciphertext + tag as base64url
return Buffer.concat([nonce, encrypted, tag]).toString('base64url');
}
export function decrypt(payload: string, key: Buffer): string {
const raw = Buffer.from(payload, 'base64url');
const nonce = raw.subarray(0, NONCE_LENGTH);
const tag = raw.subarray(raw.length - TAG_LENGTH);
const ciphertext = raw.subarray(NONCE_LENGTH, raw.length - TAG_LENGTH);
const decipher = createDecipheriv(ALGORITHM, key, nonce);
decipher.setAuthTag(tag);
return decipher.update(ciphertext, undefined, 'utf-8') + decipher.final('utf-8');
}
The bundled format looks like 6s7T8w9x... (a single base64url-encoded string). You store this directly in a TEXT column. The nonce and tag ride along with the ciphertext, so you never need to manage them separately.
You should never use a password or passphrase directly as an AES key. Passwords have far less entropy than 256 bits. Use PBKDF2 (or scrypt for newer projects) to derive a fixed-length key from the passphrase.
export function deriveKey(passphrase: string, salt: Buffer): Buffer {
return pbkdf2Sync(passphrase, salt, 600000, KEY_LENGTH, 'sha-512');
}
export function generateSalt(): Buffer {
return randomBytes(SALT_LENGTH);
}
The iteration count of 600,000 is the OWASP 2026 recommended minimum for PBKDF2-HMAC-SHA-512. If you ship this code in 2027, bump it. If you use scrypt, the cost parameters (N, r, p) should be tuned to take about 100ms of CPU time on your production hardware.
Store the salt alongside each encrypted value, or use a single application-wide salt stored in an environment variable. A per-value salt is safer because two identical plaintexts produce different ciphertexts, but it adds 32 bytes per row to the storage overhead. For most use cases, a static salt in the environment config is acceptable as long as the key is rotated periodically.
A single encryption key is a single point of failure. If the key leaks, every encrypted value is compromised. You need key rotation, and you need it to be zero-downtime.
The standard pattern is a key version table:
CREATE TABLE encryption_keys (
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
version INTEGER NOT NULL UNIQUE,
key BYTEA NOT NULL, -- encrypted with a master key from the vault
active BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
When you encrypt a value, you use the active key. When you decrypt, you look up which key was used based on the version stored alongside the ciphertext.
Modify the encrypted payload format to include the key version:
interface EncryptedPayload {
version: number;
nonce: string; // base64url
ciphertext: string;
tag: string;
}
Or pack them into a single string with a version prefix:
export function encrypt(plaintext: string, keyVersion: number, key: Buffer): string {
const nonce = randomBytes(NONCE_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, nonce);
const encrypted = Buffer.concat([
cipher.update(plaintext, 'utf-8'),
cipher.final(),
]);
const tag = cipher.getAuthTag();
// Format: v<version>:<nonce+ciphertext+tag as base64url>
const raw = Buffer.concat([nonce, encrypted, tag]);
return `v${keyVersion}:${raw.toString('base64url')}`;
}
To rotate keys:
active = false.inactive = true and the new key to active = true.The background job handles at most 1000 rows per batch so it does not compete with production traffic:
import { pool } from './db';
import { decrypt, encrypt, getKeyByVersion } from './crypto';
const BATCH_SIZE = 1000;
const OLD_VERSION = 1;
const NEW_VERSION = 2;
export async function rotateKeys(): Promise<void> {
const oldKey = await getKeyByVersion(OLD_VERSION);
const newKey = await getKeyByVersion(NEW_VERSION);
let processed = 0;
while (true) {
const { rows } = await pool.query(
`UPDATE user_secrets
SET encrypted_api_key = v.secret::text
FROM (
SELECT id,
encrypt(
decrypt(encrypted_api_key, $1::bytea),
$2::int,
$2::bytea
) AS secret
FROM user_secrets
WHERE key_version = $3
LIMIT $4
FOR UPDATE SKIP LOCKED
) v
WHERE user_secrets.id = v.id
RETURNING user_secrets.id`,
[oldKey, newKey, OLD_VERSION, BATCH_SIZE]
);
if (rows.length === 0) break;
processed += rows.length;
}
}
The FOR UPDATE SKIP LOCKED prevents the batch job from blocking writes to rows it is not processing. Each batch locks exactly 1000 rows, re-encrypts them, and moves on.
Application-layer encryption is not a silver bullet. It adds complexity, makes search impossible, and prevents the database from enforcing constraints on the encrypted column. Use it selectively.
Good candidates for encryption:
Bad candidates for encryption:
If you need search on encrypted data, consider one of these approaches:
Crypto code is the worst kind of code to get wrong: the failure mode is silent corruption or a full security bypass. Test it thoroughly.
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { encrypt, decrypt, deriveKey, generateSalt } from './crypto';
describe('encryption round-trip', () => {
const key = deriveKey('test-passphrase', generateSalt());
it('encrypts and decrypts a string', () => {
const original = 'sk_live_abc123def456';
const encrypted = encrypt(original, key);
assert.notStrictEqual(encrypted, original);
assert.strictEqual(decrypt(encrypted, key), original);
});
it('produces different ciphertexts for the same plaintext', () => {
const a = encrypt('hello', key);
const b = encrypt('hello', key);
assert.notStrictEqual(a, b);
});
it('rejects tampered ciphertexts', () => {
const encrypted = encrypt('secret', key);
const buf = Buffer.from(encrypted, 'base64url');
buf[14] ^= 0x01; // flip a bit in the ciphertext
assert.throws(() => decrypt(buf.toString('base64url'), key));
});
it('rejects a truncated payload', () => {
const encrypted = encrypt('secret', key);
assert.throws(() => decrypt(encrypted.slice(0, -10), key));
});
it('rejects decryption with a different key', () => {
const otherKey = deriveKey('different-passphrase', generateSalt());
const encrypted = encrypt('secret', key);
assert.throws(() => decrypt(encrypted, otherKey));
});
});
Run these tests with node --test crypto.test.ts and no test runner is needed (Node ships one). If you want coverage, node --test --experimental-test-coverage crypto.test.ts.
The encryption key must come from somewhere more secure than a config file checked into Git. The options, from most to least secure:
The least secure option, but the one most teams use, is a hardcoded key in a config file. Do not be that team. If you store the key in an environment variable, ensure the value is rotated at least quarterly and that the application can reload it without a full restart.
Application-layer encryption is one of those infrastructure decisions that is easy to skip during a sprint push and nearly impossible to retrofit after a breach. Designing a system where sensitive data is encrypted before it touches the database, keys are rotated without downtime, and the crypto primitives are chosen correctly from the start requires the kind of engineering discipline that comes from building production systems for years. Yojji’s teams regularly design and implement secure data pipelines, from key management and encryption utilities to full-stack applications on AWS, Azure, and Google Cloud. Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK, and their engineers specialize in the JavaScript ecosystem, cloud-native deployments, and the kind of security-first architecture that protects data at every layer of the stack.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。