← Back to dashboard
encryptiontoolingfreshReader view (for NotebookLM)

Encryption Integration Guide

What is encryption, really?

The real model

Pick the primitive, let an audited library do the math — then protect PII/PHI at the field level.

AES-256-GCM with a fresh 12-byte IV per message for at-rest data; HPKE (hybrid MLKEM768-X25519 on Node 24.7+) or libsodium sealed boxes to encrypt to a public key; Argon2id (OWASP floor 19 MiB / t=2 / p=1) for passwords. At scale, envelope encryption: a DEK encrypts data, an AWS/GCP KMS key wraps it — reached from Vercel via OIDC, since Vercel KMS only signs. For codeAmani, DoseVault PHI (HIPAA) and customer PII get field-level AES-256-GCM so the DB only holds ciphertext, plus blind indexes for lookups and masking in logs. OWASP on rolling your own crypto: don't.

Six primitives you reach for

Right category first — reversible vs one-way, who holds the key — then the implementation is mechanical.

Text
███████╗███╗   ██╗ ██████╗██████╗ ██╗   ██╗██████╗ ████████╗██╗ ██████╗ ███╗   ██╗
██╔════╝████╗  ██║██╔════╝██╔══██╗╚██╗ ██╔╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
█████╗  ██╔██╗ ██║██║     ██████╔╝ ╚████╔╝ ██████╔╝   ██║   ██║██║   ██║██╔██╗ ██║
██╔══╝  ██║╚██╗██║██║     ██╔══██╗  ╚██╔╝  ██╔═══╝    ██║   ██║██║   ██║██║╚██╗██║
███████╗██║ ╚████║╚██████╗██║  ██║   ██║   ██║        ██║   ██║╚██████╔╝██║ ╚████║
╚══════╝╚═╝  ╚═══╝ ╚═════╝╚═╝  ╚═╝   ╚═╝   ╚═╝        ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Encryption Integration Guide

Focus: pick the right primitive for the job and let an audited library do the math. Symmetric (AES-256-GCM) for data you can decrypt, hashing (Argon2id) for passwords you never can, HPKE or sealed boxes for "encrypt to a public key", and envelope encryption with a KMS for keys at scale. For codeAmani the load-bearing case is protecting PHI (DoseVault, HIPAA) and customer PII — field-level encryption, masking and blind indexes on top of these primitives.

Overview

Encryption is not one thing. The most common mistake is reaching for the wrong tool: hashing a value you need to read back later, "encrypting" a password you should never be able to recover, or hand-rolling AES with a static IV. Get the category right first; the implementation is then almost mechanical.

Four categories cover almost everything you'll touch:

  1. Symmetric encryption — one secret key encrypts and decrypts. Fast, used for bulk data. Default: AES-256-GCM (or ChaCha20-Poly1305 / XChaCha20-Poly1305). Reversible.
  2. Asymmetric (public-key) encryption — a public key encrypts, a separate private key decrypts. OWASP now recommends a hybrid public-key encryption scheme — HPKE (RFC 9180) — rather than raw RSA or a hand-built ECDH+AES combination. libsodium sealed boxes remain a fine, simple choice.
  3. Hashing — a one-way function. Not encryption: no key, no way back. Argon2id for passwords, SHA-256 for integrity, HMAC-SHA-256 when a secret key is involved.
  4. E2EE — end-to-end: only the endpoints hold keys; the server relays ciphertext it cannot read. Built from the above.

Layered on where the data lives: in transit (TLS — the platform's job, you just enforce HTTPS) vs at rest (provider disk encryption is on by default; field-level encryption and key management are your job).

Golden rule, straight from OWASP: don't roll your own crypto. Use Node's node:crypto / Web Crypto (built in), libsodium, @noble/*, hpke, jose or Google Tink.

What changed in 2026 (read this if you used an older version of this guide)

WasNow (verified 2026-10-20)
"Web Crypto in Node 20+"Node 20 is EOL (2026-04-30); Vercel deprecated it on 2026-10-01. Target Node 24 LTS "Krypton" (Vercel default; maintenance LTS from 2026-10-20) or 22 "Jod". Node 26 becomes LTS on 2026-10-28.
Argon2 needs the native argon2 addonNode 24.7+ has crypto.argon2() / argon2Sync() built in (and Web Crypto Argon2id under "Modern Algorithms"). It's a raw KDF — keep the argon2 package for PHC-string password storage.
Post-quantum is a "watch" itemNode 24.7+ (OpenSSL 3.5) ships ML-KEM-512/768/1024 (crypto.encapsulate / decapsulate), ML-DSA and SLH-DSA keys. hpke@1.1.7 runs MLKEM768-X25519 hybrid HPKE on Node today.
"Encrypt to a public key: X25519 / RSA-OAEP"OWASP Cryptographic Storage now says: use HPKE; X25519 is key agreement, not encryption on its own.
"KMS: AWS, GCP, Cloudflare, Vercel"Vercel KMS (Beta) only signs JWTs/messages (RS/PS/ES keys); it has no encrypt/decrypt. Envelope encryption = AWS KMS or GCP Cloud KMS, authenticated from Vercel with OIDC federation.
Supabase pgsodium for column encryptionSupabase marks pgsodium pending deprecation and recommends against its Transparent Column Encryption; use Supabase Vault for DB-side secrets and app-layer encryption for PHI.
@noble/ciphers 2.32.4.0 (ESM-only, .js subpath imports).

Official Documentation

SourceURLWhat it covers
Node.js 24 cryptohttps://nodejs.org/docs/latest-v24.x/api/crypto.htmlcreateCipheriv GCM/ChaCha20-Poly1305, argon2, encapsulate/decapsulate, ML-KEM/ML-DSA keys, hkdf, timingSafeEqual
Node.js 24 Web Cryptohttps://nodejs.org/docs/latest-v24.x/api/webcrypto.htmlcrypto.subtle; "Modern Algorithms" (ML-KEM, ML-DSA, Argon2, ChaCha20-Poly1305, AES-OCB) — Stability 1.1
MDN — SubtleCrypto.encrypthttps://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encryptAES-GCM in browsers/Edge, IV rules
OWASP Cryptographic Storagehttps://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.htmlAlgorithms, modes, HPKE, envelope encryption, key separation
OWASP Password Storagehttps://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.htmlArgon2id / scrypt / bcrypt / PBKDF2 parameters, peppering
OWASP Post-Quantum Cryptographyhttps://cheatsheetseries.owasp.org/cheatsheets/Post_Quantum_Cryptography_Cheat_Sheet.htmlML-KEM, hybrid TLS (X25519MLKEM768), ML-DSA migration
NIST FIPS 203 / 204 / 205https://csrc.nist.gov/pubs/fips/203/finalML-KEM, ML-DSA, SLH-DSA (final, Aug 2024)
libsodium sealed boxeshttps://doc.libsodium.org/public-key_cryptography/sealed_boxesAnonymous public-key encryption
hpke (panva)https://github.com/panva/hpkeRFC 9180 HPKE incl. ML-KEM and hybrid KEMs
AWS KMShttps://docs.aws.amazon.com/kms/latest/developerguide/overview.htmlGenerateDataKey, Decrypt, encryption context
Google Cloud KMS envelope encryptionhttps://cloud.google.com/kms/docs/envelope-encryptionDEK/KEK model, encrypt/decrypt
Vercel KMShttps://vercel.com/docs/kmsManaged signing keys (Beta)

The taxonomy at a glance

CategoryReversible?Key modelReach forcodeAmani example
SymmetricYesone shared keyAES-256-GCMEncrypt a PHI column at rest
Public-keyYespublic + privateHPKE (RFC 9180), libsodium sealed boxEncrypt to a clinician's device key
HashingNonone (HMAC: secret key)Argon2id (passwords), SHA-256 (integrity), HMAC-SHA-256 (blind index, webhooks)Store a PIN; look up a patient by phone
E2EEYes (endpoints only)per-party keysHPKE / sealed box / libsignalPatient-to-clinician message

Encryption vs hashing — never blur them: encryption is reversible with the key; hashing is one-way with no key. Passwords get hashed; values you must display later get encrypted. "Decrypt the password to email it to the user" is a design bug.


Runtime matrix (what runs where)

PrimitiveNode 22 LTSNode 24 LTS (Vercel default)Edge / Workers / browser
AES-256-GCMnode:crypto + crypto.subtlesamecrypto.subtle
ChaCha20-Poly1305node:cryptonode:crypto + crypto.subtle (Modern Algos)@noble/ciphers
Argon2idnpm argon2 (native addon)npm argon2, or built-in crypto.argon2() (v24.7+)not for password storage — hash on a Node function
ML-KEM / ML-DSA / SLH-DSAnonode:crypto (v24.7+, OpenSSL 3.5)@noble/post-quantum
HPKEhpke (classic KEMs)hpke incl. KEM_MLKEM768_X25519hpke (classic KEMs; Workers: no ML-KEM per its matrix)
Sealed boxlibsodium-wrapperssamesame (WASM)

Check the OpenSSL your function actually runs with process.versions.openssl (Node 24.22.0 bundles 3.5.8).


Symmetric: AES-256-GCM

AES-256-GCM is OWASP's preferred default (GCM/CCM first preference). It is authenticated — tampering, a wrong key, or wrong AAD makes decryption throw.

Non-negotiable rules:

  • 12-byte IV, unique per encryption under a key. Reuse destroys GCM. Random IVs are fine up to ~2³² messages per key (NIST SP 800-38D) — rotate well before, or use one DEK per record (envelope encryption).
  • 16-byte tag — never truncate.
  • Keys server-side only — env/KMS, never NEXT_PUBLIC_*, never in the client bundle.
  • Version your ciphertext (v1.…) so a rotation or algorithm change doesn't strand old rows.

Node runtime (examples/aead.ts, wire format v1.iv.tag.ct, base64url):

TypeScript
import { createCipheriv, randomBytes } from "node:crypto";

export function encrypt(plaintext: string, key: Buffer, aad?: Buffer): string {
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
  if (aad) cipher.setAAD(aad);
  const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const tag = cipher.getAuthTag(); // only valid AFTER final()
  return ["v1", iv.toString("base64url"), tag.toString("base64url"), ct.toString("base64url")].join(".");
}

Edge / Workers / browser — Web Crypto (examples/webcrypto-aes-gcm.ts):

TypeScript
// lib/crypto/aes-gcm.ts — AES-256-GCM via Web Crypto (Node 22+/24 LTS, Edge, Workers, browser).
const IV_BYTES = 12; // GCM standard; MUST be unique per message under one key

const b64 = (u: Uint8Array): string => btoa(String.fromCharCode(...u));
const unb64 = (s: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));

/** Import a 32-byte (256-bit) raw key as a non-extractable AES-GCM CryptoKey. */
export async function importKey(raw: Uint8Array<ArrayBuffer>): Promise<CryptoKey> {
  if (raw.byteLength !== 32) throw new Error("AES-256 key must be 32 bytes");
  return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
}

/** Encrypt UTF-8 text → { iv, ciphertext } (base64). The 16-byte GCM tag is appended to ciphertext. */
export async function encrypt(plaintext: string, key: CryptoKey, aad?: Uint8Array<ArrayBuffer>) {
  const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); // fresh every call
  const params: AesGcmParams = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
  const ct = await crypto.subtle.encrypt(params, key, new TextEncoder().encode(plaintext));
  return { iv: b64(iv), ciphertext: b64(new Uint8Array(ct)) };
}

/** Decrypt; rejects (OperationError) if the tag fails — tampered data, wrong key or wrong AAD. */
export async function decrypt(
  payload: { iv: string; ciphertext: string },
  key: CryptoKey,
  aad?: Uint8Array<ArrayBuffer>,
): Promise<string> {
  const iv = unb64(payload.iv);
  const params: AesGcmParams = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
  const pt = await crypto.subtle.decrypt(params, key, unb64(payload.ciphertext));
  return new TextDecoder().decode(pt);
}

AAD binds context. Pass table:rowId as AAD so a ciphertext copied to another row fails to decrypt. Cheap, strong defence against ciphertext swapping.

TypeScript ≥ 5.7 note: Web Crypto's BufferSource now wants Uint8Array<ArrayBuffer>; a bare Uint8Array (which may be backed by SharedArrayBuffer) is a type error under --strict. The snippet above is typed accordingly (checked with TS 5.9.3 and 7.0.2).


HPKE (RFC 9180) combines a KEM, a KDF and an AEAD into one vetted construction — OWASP's current recommendation. The zero-dependency hpke package (by panva, the jose author) runs on Node, Deno, Bun, Workers and browsers, and on Node 24 supports the post-quantum hybrid KEM_MLKEM768_X25519. Base mode doesn't authenticate the sender; use an auth/PSK mode if you need that.

TypeScript
// examples/hpke-pq.mts — hpke@1.1.7, Node 24 LTS (verified running on Node 24.15.0)
import * as HPKE from "hpke";

const suite = new HPKE.CipherSuite(HPKE.KEM_MLKEM768_X25519, HPKE.KDF_HKDF_SHA256, HPKE.AEAD_AES_256_GCM);

const recipient = await suite.GenerateKeyPair();
const publicKeyBytes = await suite.SerializePublicKey(recipient.publicKey); // publish these

const info = new TextEncoder().encode("codeamani/dosevault/message/v1");
const pub = await suite.DeserializePublicKey(publicKeyBytes);
const { encapsulatedSecret, ciphertext } = await suite.Seal(pub, new TextEncoder().encode("BP 120/80"), { info });

const plaintext = await suite.Open(recipient, encapsulatedSecret, ciphertext, { info });

The full example falls back to KEM_DHKEM_X25519_HKDF_SHA256 where ML-KEM isn't available (browsers, Workers). Store encapsulatedSecret (1,120 bytes for the hybrid KEM) next to the ciphertext.

libsodium sealed boxes (X25519 + XSalsa20-Poly1305) are still a simple, safe "encrypt to a public key" — anonymous sender, classical only:

TypeScript
// lib/crypto/sealed-box.ts — anonymous public-key encryption with libsodium (libsodium-wrappers 0.8.4)
import sodium from "libsodium-wrappers";

/** Recipient generates a keypair once; publishes publicKey, keeps privateKey secret. */
export async function newKeypair() {
  await sodium.ready;
  const { publicKey, privateKey } = sodium.crypto_box_keypair();
  return { publicKey, privateKey }; // Uint8Array, 32 bytes each (X25519)
}

/** Anyone with the recipient's public key can seal a message to them. */
export async function seal(message: string, recipientPublicKey: Uint8Array): Promise<Uint8Array> {
  await sodium.ready;
  // ephemeral keypair is generated + erased internally; sender stays anonymous
  return sodium.crypto_box_seal(sodium.from_string(message), recipientPublicKey);
}

/** Only the recipient (holding both keys) can open it; throws on tampering. */
export async function open(
  sealed: Uint8Array,
  recipientPublicKey: Uint8Array,
  recipientPrivateKey: Uint8Array,
): Promise<string> {
  await sodium.ready;
  const opened = sodium.crypto_box_seal_open(sealed, recipientPublicKey, recipientPrivateKey);
  return sodium.to_string(opened);
}

Always await sodium.ready before any sodium.* call (WASM loads async). libsodium-wrappers 0.8.x ships its own types — don't install @types/libsodium-wrappers (now a deprecated stub).

RSA only for interop: RSA-OAEP, ≥ 2048-bit keys; never PKCS#1 v1.5 encryption.


Post-quantum: what to do now

  • Standards (NIST): FIPS 203 ML-KEM, FIPS 204 ML-DSA, FIPS 205 SLH-DSA — final since Aug 2024. FN-DSA (FIPS 206) and HQC (selected Mar 2025) are not final as of 2026-10-20. NIST plans to deprecate and remove quantum-vulnerable algorithms (RSA, ECC) from its standards by 2035 (IR 8547).
  • Symmetric crypto is fine. AES-256 and SHA-256/384 stay; PQ changes key establishment and signatures.
  • Harvest-now-decrypt-later is the real risk for long-lived PHI: anything you encrypt to a public key today should use a hybrid KEM (HPKE MLKEM768-X25519) where both ends support it.
  • Transport: hybrid TLS key exchange X25519MLKEM768 is standardised in RFC 10024 (Aug 2026); it's negotiated by your platform/CDN, not your code.
  • Signatures: plan a separate migration (ML-DSA). AWS KMS supports ML_DSA_44/65/87 keys; GCP Cloud KMS supports ML-KEM-768/1024 and PQ signatures.
  • Don't hand-combine classical + PQ. Use the protocol (HPKE, TLS) — OWASP PQC Cheat Sheet.

Raw ML-KEM in Node 24.7+ (examples/ml-kem-node.mts) — it only agrees a 32-byte secret; derive an AES key with HKDF:

TypeScript
import { decapsulate, encapsulate, generateKeyPairSync, hkdfSync } from "node:crypto";

const { publicKey, privateKey } = generateKeyPairSync("ml-kem-768");
const { sharedKey, ciphertext } = encapsulate(publicKey);            // sender
const recovered = decapsulate(privateKey, ciphertext);                // recipient
const aesKey = Buffer.from(hkdfSync("sha256", recovered, Buffer.alloc(0), "app/v1/aes-256-gcm", 32));

Hashing: passwords and integrity (not encryption)

  • Password storage → Argon2id. OWASP minimum (re-verified 2026-10-20): m=19456 KiB (19 MiB), t=2, p=1. OWASP lists equivalent floors — 46 MiB/t=1, 12 MiB/t=3, 9 MiB/t=4, 7 MiB/t=5 (all p=1). RFC 9106's "second recommended option" is 64 MiB, t=3, p=4, which is also argon2's default — prefer it when function memory allows. Fallbacks: scrypt N=2¹⁷, r=8, p=1; bcrypt legacy only, cost ≥ 10, 72-byte input limit; PBKDF2-HMAC-SHA-256 ≥ 600,000 iterations when FIPS-140 is required. Optional pepper (HMAC key held in a vault/HSM, never in the DB).
  • Integrity / fingerprinting → SHA-256. Never for passwords.
  • Keyed lookups / webhooks → HMAC-SHA-256, compared with crypto.timingSafeEqual.
TypeScript
// lib/crypto/password.ts — server-side ONLY (argon2@0.45.1, native N-API addon)
import * as argon2 from "argon2";

const ARGON2_OPTIONS = { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 } as const;

export const hashPassword = (plain: string) => argon2.hash(plain, ARGON2_OPTIONS); // PHC string, 16-byte random salt
export const verifyPassword = (hash: string, plain: string) => argon2.verify(hash, plain); // false on mismatch, throws on bad hash
export const needsRehash = (hash: string) => argon2.needsRehash(hash, ARGON2_OPTIONS); // pass the SAME options

Node 24.7+ built-in crypto.argon2() returns raw key bytes (no PHC string, no needsRehash). Use it to derive a key from a passphrase (examples/node-argon2-kdf.mts); keep the argon2 package for password storage. argon2@1.0.0-alpha.1 sits on the next tag — don't adopt until it's latest.

With Clerk as the auth provider we don't store passwords at all. Hash yourself only for systems Clerk doesn't cover.


In transit vs at rest

In transitAt rest (disk)At rest (field-level)
ThreatEavesdropper / MITMStolen disk / backupLeaked dump, SQL injection, over-broad RLS, curious operator
MechanismTLS 1.2+/1.3Provider AES-256App-layer AES-256-GCM + envelope keys
WhoPlatform (Vercel, Cloudflare, Neon/Supabase enforce TLS)Provider, on by defaultYou
  • Neon: TLS required on every connection; data at rest AES-256 (NVMe hardware encryption, keys in AWS KMS / Azure Key Vault). pgcrypto is available if the DB must do crypto.
  • Supabase: projects encrypted at rest by default. Vault stores secrets with libsodium AEAD; pgsodium is pending deprecation — don't use its Transparent Column Encryption.
  • Disk encryption does nothing against a compromised app role that can SELECT plaintext — hence field-level encryption for PHI. Keep keys out of the database (prefer app-layer encryption over pgcrypto for PHI).

Envelope encryption & KMS

You don't encrypt millions of rows with one key in an env var. Envelope encryption (OWASP):

  • A DEK (data encryption key) encrypts the data with AES-256-GCM — ideally one per record or per tenant.
  • A KEK in a KMS/HSM wraps each DEK. The KEK never leaves the KMS; it must be at least as strong as the DEK.
  • Store the wrapped DEK next to the ciphertext. Rotating the KEK = re-wrap DEKs, not re-encrypt data. A leaked wrapped DEK is useless without KMS access.

Which KMS

KMSEnvelope encryption?Pricing (verified 2026-10-20)Notes
AWS KMSYes — GenerateDataKey + Decrypt$1/key/month (rotations add $1 for the first two, then capped); symmetric requests $0.03 per 10,000; free tier 20,000 requests/month (asymmetric excluded)EncryptionContext = AAD, logged in CloudTrail. ML-DSA signing keys GA.
GCP Cloud KMSYes — generate DEK locally, wrap with encryptSoftware key version $0.06/month, HSM $1.00/month; crypto ops $0.03 per 10,000 (some HSM ops $0.15)additionalAuthenticatedData = AAD. ML-KEM-768/1024 supported.
Vercel KMS (Beta)No — signing only (RS*/PS*/ES*, default RS512; no HS*)Beta, all plans; no price published@vercel/kms signJWT / signMessage; JWKS at https://kms.vercel.com/<issuerId>/jwks.json. FIPS 140-3 L1 OpenSSL provider. Use it to sign tokens without a private key in env — not to encrypt data.

AWS KMS from a Vercel Function (OIDC, no long-lived AWS keys)

Non-secret configuration (put these in Vercel project settings as plain env, not secrets):

SettingExampleSecret?
AWS_REGIONus-east-1No
AWS_ROLE_ARNarn:aws:iam::<account>:role/<app>-kmsNo
KMS_KEY_IDalias/dosevault-phiNo
TypeScript
// examples/envelope-aws-kms.ts (excerpt) — @aws-sdk/client-kms 3.1153.0 + @vercel/oidc-aws-credentials-provider 3.3.13
import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from "@aws-sdk/client-kms";
import { awsCredentialsProvider } from "@vercel/oidc-aws-credentials-provider";
import { encrypt } from "./aead.js";

const kms = new KMSClient({
  region: process.env.AWS_REGION,
  credentials: awsCredentialsProvider({ roleArn: process.env.AWS_ROLE_ARN ?? "" }),
});

export async function sealField(plaintext: string, ctx: { table: string; rowId: string }) {
  const { Plaintext, CiphertextBlob } = await kms.send(
    new GenerateDataKeyCommand({ KeyId: process.env.KMS_KEY_ID, KeySpec: "AES_256", EncryptionContext: ctx }),
  );
  if (!Plaintext || !CiphertextBlob) throw new Error("KMS returned no data key");
  const dek = Buffer.from(Plaintext);
  try {
    return {
      wrappedDek: Buffer.from(CiphertextBlob).toString("base64"),
      payload: encrypt(plaintext, dek, Buffer.from(`${ctx.table}:${ctx.rowId}`)),
    };
  } finally {
    dek.fill(0); // drop the plaintext DEK
  }
}
// openField(): DecryptCommand({ KeyId, CiphertextBlob, EncryptionContext: ctx }) → decrypt(payload, dek, aad)

GCP equivalent: examples/envelope-gcp-kms.ts (KeyManagementServiceClient.encrypt/decrypt with additionalAuthenticatedData). For very high volume, cache DEKs briefly or use the AWS Encryption SDK (@aws-crypto/client-node 5.0.2) with its caching materials manager — KMS calls cost money and add latency.

Rotation triggers (OWASP): suspected compromise, end of cryptoperiod, or usage limits (e.g. AES-GCM random-IV message count). Turn on automatic KEK rotation in AWS/GCP.


PII / PHI: field-level encryption, masking, blind indexes, tokenization

DoseVault handles PHI under HIPAA; every codeAmani product handles customer PII (US-first; KDPA 2019 also applies to Kenya-targeted projects). Disk encryption alone isn't enough.

1. Field-level (application-layer) encryption

Encrypt sensitive columns before they reach Postgres; decrypt in the app. The DB only ever sees ciphertext.

TypeScript
// Storing a PHI field — envelope-encrypt at the app boundary, store only ciphertext columns.
import { sealField } from "./envelope-aws-kms.js";
import { blindIndex } from "./mask.js";

interface RecordsTable {
  insert(row: {
    id: string;
    patient_phone_bidx: string; // blind index for lookups — never the phone itself
    diagnosis_dek: string;      // wrapped DEK (KMS CiphertextBlob, base64)
    diagnosis_ct: string;       // "v1.iv.tag.ct"
  }): Promise<void>;
}

export async function storeDiagnosis(
  db: RecordsTable,
  rec: { id: string; phone: string; diagnosis: string },
  bidxKey: Buffer,
): Promise<void> {
  const { wrappedDek, payload } = await sealField(rec.diagnosis, { table: "records", rowId: rec.id });
  await db.insert({
    id: rec.id,
    patient_phone_bidx: blindIndex(rec.phone, bidxKey),
    diagnosis_dek: wrappedDek,
    diagnosis_ct: payload,
  });
}

2. Blind indexes (search without plaintext)

Encrypted columns can't be WHEREd. Store a keyed HMAC-SHA-256 of the normalised value next to it and query on that. Use a separate HMAC key from the encryption key. Leaks equality (same input → same index), so only index what you must look up.

3. Masking (display / logs)

TypeScript
// Mask an M-Pesa phone (always 254XXXXXXXXX) and an ID for UI / logs
export const maskPhone = (p: string): string => p.replace(/^(\d{3})\d{6}(\d{3})$/, "$1******$2"); // 254******149
export const maskId = (id: string): string => (id.length <= 4 ? "****" : "****" + id.slice(-4));

// Blind index: deterministic, keyed lookup token for an encrypted column (e.g. find a
// patient by phone without storing the phone in plaintext). HMAC key ≠ encryption key.
import { createHmac } from "node:crypto";
export const blindIndex = (value: string, hmacKey: Buffer): string =>
  createHmac("sha256", hmacKey).update(value.normalize("NFKC").toLowerCase()).digest("base64url");

Never log raw PII/PHI. Mask emails, phone numbers, patient ids — and, on Kenya-targeted projects, M-Pesa phones and CheckoutRequestIDs — before they reach Sentry or logs. Structured logging only.

4. Tokenization

Replace a sensitive value with a meaningless token; keep the real value in one locked-down vault. For card data, Stripe already tokenizes — never store PANs; that keeps us out of most PCI DSS scope.


Tokens and cookies: jose

For an encrypted, tamper-proof token or cookie, don't invent a format — use JWE via jose@6.2.13 (dir + A256GCM). For signed tokens issued from Vercel without holding a private key, Vercel KMS signJWT is the managed option.

TypeScript
import { CompactEncrypt, compactDecrypt } from "jose";

const key = crypto.getRandomValues(new Uint8Array(32)); // in prod: 32 bytes from env/KMS
const jwe = await new CompactEncrypt(new TextEncoder().encode(JSON.stringify({ sub: "user_123" })))
  .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
  .encrypt(key);
const { plaintext } = await compactDecrypt(jwe, key);

Secrets

Only real secrets go in the vault. Generate each with a CSPRNG (openssl rand -base64 32) per environment, store in Vercel env (Sensitive) / the codeAmani secrets vault, never in the repo:

Bash
ENCRYPTION_KEY_B64=base64-32-random-bytes-placeholder
BLIND_INDEX_KEY_B64=base64-32-random-bytes-placeholder

With envelope encryption in production, ENCRYPTION_KEY_B64 is only a dev/local fallback; the KEK lives in KMS and needs no env secret (OIDC federation).


E2EE in one paragraph

End-to-end encryption means the server only ever holds ciphertext. For one-shot messages, HPKE (or a sealed box) is genuine E2EE: encrypt client-side to the recipient's public key, store opaque bytes, only the recipient's private key opens it. For live conversations, Signal's double ratchet adds forward secrecy and post-compromise security — don't implement it yourself; use libsignal or a vetted SDK. Key distribution and device verification are the hard part, not the cipher.


Security checklist

  • AES-256-GCM for symmetric at-rest; fresh 12-byte IV per message, 16-byte tag, versioned ciphertext.
  • Argon2id for passwords (≥ 19 MiB / t=2 / p=1, or 64 MiB / t=3 / p=4); SHA-256 only for integrity.
  • HPKE (hybrid MLKEM768-X25519 where supported) or sealed boxes for public-key encryption; RSA-OAEP ≥ 2048 only for interop.
  • Keys server-side only — KMS / env, never NEXT_PUBLIC_*.
  • Envelope encryption with AWS/GCP KMS via Vercel OIDC; wrapped DEK beside ciphertext; KEK never leaves KMS.
  • Field-level encryption for PHI/PII columns; blind index (separate HMAC key) for lookups.
  • AAD / EncryptionContext binds ciphertext to its row.
  • Mask PII before logging; never log raw payloads.
  • Audited libraries only; constant-time compares (timingSafeEqual) for secrets.
  • TLS 1.2+ everywhere; HTTPS-only callbacks.
  • Runtime ≥ Node 22 LTS (24 preferred); Node 20 is EOL.
  • PQ plan: inventory public-key uses; hybrid KEM for long-lived confidential data; ML-DSA signature migration on the roadmap.

codeAmani notes

  • PHI (DoseVault) is the bar. HIPAA requires protecting ePHI at rest and in transit; we meet it with field-level AES-256-GCM + KMS envelope encryption, not disk encryption alone (a compromised app role still reads plaintext). KDPA 2019 applies additionally on Kenya-targeted projects.
  • Keys never touch the client. Symmetric/private keys live in KMS or Vercel env, server-side only. Browser-side crypto only for E2EE flows where the browser legitimately holds the user's own key.
  • KMS choice: AWS KMS (or GCP Cloud KMS when the project is already on Google Cloud) reached via Vercel OIDC federation — no static cloud keys in env. Vercel KMS is for signing tokens, not encrypting data.
  • Runtime: Node 24 LTS on Vercel ("engines": { "node": "24.x" }). Crypto routes run on the Node runtime, not Edge, when they need argon2, KMS SDKs or ML-KEM.
  • Payments: Stripe (default) tokenizes cards — we never see or store PANs; verify Stripe webhooks with the signing secret (stripe.webhooks.constructEvent). On Kenya-targeted projects only, mask M-Pesa phones (254XXXXXXXXX) and CheckoutRequestID in every log, and store retained identifiers encrypted or as blind indexes.
  • Prefer audited libs, explicitly. node:crypto / Web Crypto, libsodium-wrappers, @noble/*, hpke, jose, Tink. OWASP on custom crypto: don't.
  • Auth passwords → Clerk. We store no passwords where Clerk owns auth; Argon2id only for the rare system it doesn't cover.
  • AI routing: never send raw PHI/PII to Claude/OpenAI/HuggingFace prompts unless the project's BAA/DPA allows it; mask or tokenize first.
  • African-market note (Kenya-targeted projects): prefer libsodium-wrappers/@noble over large crypto bundles on the client to keep JS small for 2G/3G Android users; do heavy crypto server-side.