Derive keys from a password

Turn a passphrase into an encryption key with PBES2, once at start-up or per token, and know when a generated key is the better choice.

A password is not a key: it's short, guessable and not random. PBES2 (RFC 7518 §4.8) runs it through PBKDF2 hundreds of thousands of times with a salt, so every guess costs an attacker the same work, and the result is an AES key-wrapping key. The same password, salt and iteration count always give the same key. Use it when a person or an operator holds a passphrase and no key can be stored for them; when you can store a key, generate one instead, because no iteration count makes a weak password strong.

#Before you start

  • PBES2 is for encryption only: it gives you a key for encrypt() and decrypt(), never one that signs.
  • The salt is not secret, but it has to stay the same for as long as the key does. Use 16 random bytes or more, generated once; at least 8 bytes is required (RFC 7518 §4.8.1.1).
  • Iterations start at 1000 (RFC 7518 §4.8.1.2). 600 000 with PBES2-HS256+A128KW matches the OWASP guidance for PBKDF2-HMAC-SHA256 and is what encrypt() uses by default.
  • Every derivation takes as long as those iterations do, on purpose. Keep it out of hot paths.

#Derive a key once from a passphrase

When one configured passphrase protects many tokens, derive the key at start-up and reuse it:

passphrase-key.ts
import { deriveJWKFromPassword } from "unjwt/jwk";
import { decrypt, encrypt } from "unjwt/jwe";

const passphrase = process.env.EXPORT_PASSPHRASE;
const salt = process.env.EXPORT_SALT; // random, generated once, not secret
if (!passphrase || !salt) throw new Error("EXPORT_PASSPHRASE and EXPORT_SALT must be set");

// Runs PBKDF2 once, here; every token after this is an ordinary A128KW encryption.
const exportKey = await deriveJWKFromPassword(passphrase, {
  alg: "PBES2-HS256+A128KW",
  salt,
  iterations: 600_000,
  kid: "exports-2026",
});

export interface ExportManifest {
  accountId: string;
  files: string[];
}

export function sealManifest(manifest: ExportManifest) {
  return encrypt(manifest, exportKey);
}

export async function openManifest(token: string) {
  const { payload } = await decrypt<ExportManifest>(token, exportKey);
  return payload;
}
  • The derived key: an ordinary oct JWK with alg: "A128KW", the AES Key Wrap part of the PBES2 algorithm. Tokens sealed with it are A128KW tokens, and no PBKDF2 runs when you encrypt or decrypt.
  • Salt and count are configuration: change either, or the passphrase, and you get a different key that opens none of the earlier tokens.
  • kid: written into each token's header. Without your own, the key is named by its thumbprint.
PBES2 algPBKDF2 hashDerived key algKey size
PBES2-HS256+A128KWSHA-256A128KW16 bytes
PBES2-HS384+A192KWSHA-384A192KW24 bytes
PBES2-HS512+A256KWSHA-512A256KW32 bytes

deriveKeyFromPassword takes the same options and returns a CryptoKey that can't be exported, or a JWK with toJWK: true.

#Let each token carry its own salt

Pass the password itself to encrypt() and decrypt(), and every token gets a fresh random salt, written into its header with the count as p2s and p2c:

const token = await encrypt({ accountId: "acct_9f8e" }, "orbit-lantern-quarry-velvet");
// header: { p2c: 600000, p2s: "ik6ef4nB0_vqd7WSBCQEOw", alg: "PBES2-HS256+A128KW", enc: "A256GCM", typ: "JWT" }

Prefer this when tokens are rare and a person types the password, such as an export they unlock by hand: nothing but the password needs keeping. Prefer the derived key when the same passphrase opens many tokens, since each of these runs PBKDF2 on both sides. Encrypt a payload covers the options.

#Limits on incoming tokens

A token's p2c is chosen by whoever made it, and a huge one would burn your CPU. decrypt() holds every token to these bounds:

BoundDefaultWhere to change it
Lowest p2c accepted1000minIterations
Highest p2c accepted600 000maxIterations
PBKDF2 iterations one call may spend in all2 400 000limits.pbes2Iterations

A token that asks for more is refused with ERR_JWE_INVALID before the work starts. Limits explains the budget. deriveJWKFromPassword has no upper bound: the count there is yours, not a token's.

#When it fails

SituationWhat happens
alg is not one of the three PBES2 algorithmsThrows ERR_JWK_UNSUPPORTED.
The salt is under 8 bytes (a string is measured as UTF-8 bytes)Throws ERR_INVALID_OPTION.
iterations is below 1000, not a whole number, or not a numberThrows ERR_INVALID_OPTION.
password is neither a string nor bytes, or options isn't an objectThrows ERR_INVALID_OPTION.
kid is neither a string nor false, or metadata sets alg, kty, key_ops, ext or kThrows ERR_INVALID_OPTION.
A token opened with a different passphrase, salt or countdecrypt() throws ERR_JWE_DECRYPTION_FAILED.

Handle errors lists every code.

#Options

deriveJWKFromPassword(password, options) and deriveKeyFromPassword(password, options):

OptionDefaultNotes
algrequiredA PBES2 algorithm, from the table above.
saltrequiredText or bytes, 8 bytes or more.
iterationsrequiredA whole number, 1000 or more.
keyUsage["wrapKey", "unwrapKey"]Written as key_ops on the JWK only when you pass it.
kidthe RFC 7638 thumbprintderiveJWKFromPassword. A string is used as given, false sets none.
use, x5c, …nonederiveJWKFromPassword. Metadata merged onto the JWK.
toJWKfalsederiveKeyFromPassword. Return a JWK instead of a CryptoKey.
extractablefalsederiveKeyFromPassword. Ignored with toJWK.

#Going further

  • Store user passwords for login: that's password hashing, not key derivation; use a password hash such as Argon2.
  • PBES2 next to the other choices: Choose encryption algorithms.
  • Wrap a key under a password yourself: wrapKey with PBES2-*, where p2s and p2c are required.