惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
H
Help Net Security
The Cloudflare Blog
Y
Y Combinator Blog
A
Arctic Wolf
Cyberwarzone
Cyberwarzone
G
Google Developers Blog
Recent Announcements
Recent Announcements
S
SegmentFault 最新的问题
Microsoft Security Blog
Microsoft Security Blog
WordPress大学
WordPress大学
博客园 - Franky
罗磊的独立博客
Martin Fowler
Martin Fowler
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 三生石上(FineUI控件)
N
News and Events Feed by Topic
F
Fortinet All Blogs
N
News | PayPal Newsroom
J
Java Code Geeks
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
博客园 - 聂微东
S
Securelist
C
CERT Recently Published Vulnerability Notes
小众软件
小众软件
Cisco Talos Blog
Cisco Talos Blog
S
Security Affairs
NISL@THU
NISL@THU
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
AWS News Blog
AWS News Blog
GbyAI
GbyAI
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Vulnerabilities – Threatpost
D
Docker
P
Proofpoint News Feed
W
WeLiveSecurity
Help Net Security
Help Net Security
The GitHub Blog
The GitHub Blog
The Last Watchdog
The Last Watchdog
The Hacker News
The Hacker News
博客园 - 叶小钗

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Application-Level Encryption with Node.js node:crypto: AES-256-GCM, Key Derivation, and Rotation
The Practica · 2026-06-24 · via The Practical Developer

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.

The encryption utility

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.

Key derivation: turning a passphrase into a key

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.

Key management and rotation

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:

  1. Insert a new key with active = false.
  2. Re-encrypt all values that use the old key. This is a background job, not a migration that blocks writes. Read the plaintext by decrypting with the old key, encrypt with the new key, write it back.
  3. Once every value is migrated, set the old key to inactive = true and the new key to active = true.
  4. Delete the old key or keep it as a fallback for any values you missed.

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.

What to encrypt and what not to encrypt

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:

  • API keys, tokens, and secrets from third-party services (Stripe, OpenAI, AWS, GitHub).
  • Personal Identifiable Information (PII) that you store for compliance reasons but do not query on: national IDs, tax identifiers, phone numbers.
  • Session tokens and refresh tokens stored in the database for revocation lookups.
  • Encrypted configuration values that should never appear in logs or backups.

Bad candidates for encryption:

  • Fields you need to search, sort, or index. Encrypted values are opaque blobs. Postgres cannot index them, filter on them, or join on them.
  • Foreign keys. A foreign key must be visible to the database to enforce referential integrity.
  • Fields used in WHERE clauses for normal querying. If you need to look up a user by email, do not encrypt the email column.
  • High-cardinality fields encrypted with a static salt. If you encrypt email addresses with a static salt, the ciphertext is deterministic and essentially a hash. An attacker can brute-force common emails against the ciphertext column.

If you need search on encrypted data, consider one of these approaches:

  • Hash for equality lookups. Store a SHA-256 hash of the field alongside the encrypted value. Query by the hash, decrypt the result. The hash leaks that two rows have the same value, so only use this for low-cardinality or low-sensitivity fields.
  • Application-side search. Load the encrypted values, decrypt them in application memory, filter there. This works for small datasets but does not scale beyond a few thousand rows.
  • Client-side encryption. The server never sees the plaintext at all. The client encrypts before sending, decrypts after receiving. This works for end-to-end encrypted applications but shifts the key management problem to the client.

Testing the encryption code

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.

Key storage

The encryption key must come from somewhere more secure than a config file checked into Git. The options, from most to least secure:

  1. Hardware Security Module (HSM) or cloud KMS. AWS KMS, GCP Cloud KMS, or Azure Key Vault. The key never leaves the HSM; your application calls an API to encrypt and decrypt. This is the gold standard but adds latency and cost.
  2. Environment variable injected at deploy time. The key is set in the deployment pipeline from a secrets manager (Vault, AWS Secrets Manager, GitHub Actions secrets) and never written to disk or source control.
  3. Encrypted config file with a separate bootstrap key injected as an environment variable. Better than plaintext on disk, but the bootstrap key is still in an env var.

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.

A note from Yojji

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.