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()anddecrypt(), 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+A128KWmatches the OWASP guidance for PBKDF2-HMAC-SHA256 and is whatencrypt()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:
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
octJWK withalg: "A128KW", the AES Key Wrap part of the PBES2 algorithm. Tokens sealed with it areA128KWtokens, 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 alg | PBKDF2 hash | Derived key alg | Key size |
|---|---|---|---|
PBES2-HS256+A128KW | SHA-256 | A128KW | 16 bytes |
PBES2-HS384+A192KW | SHA-384 | A192KW | 24 bytes |
PBES2-HS512+A256KW | SHA-512 | A256KW | 32 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:
| Bound | Default | Where to change it |
|---|---|---|
Lowest p2c accepted | 1000 | minIterations |
Highest p2c accepted | 600 000 | maxIterations |
| PBKDF2 iterations one call may spend in all | 2 400 000 | limits.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
| Situation | What happens |
|---|---|
alg is not one of the three PBES2 algorithms | Throws 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 number | Throws ERR_INVALID_OPTION. |
password is neither a string nor bytes, or options isn't an object | Throws ERR_INVALID_OPTION. |
kid is neither a string nor false, or metadata sets alg, kty, key_ops, ext or k | Throws ERR_INVALID_OPTION. |
| A token opened with a different passphrase, salt or count | decrypt() throws ERR_JWE_DECRYPTION_FAILED. |
Handle errors lists every code.
#Options
deriveJWKFromPassword(password, options) and deriveKeyFromPassword(password, options):
| Option | Default | Notes |
|---|---|---|
alg | required | A PBES2 algorithm, from the table above. |
salt | required | Text or bytes, 8 bytes or more. |
iterations | required | A whole number, 1000 or more. |
keyUsage | ["wrapKey", "unwrapKey"] | Written as key_ops on the JWK only when you pass it. |
kid | the RFC 7638 thumbprint | deriveJWKFromPassword. A string is used as given, false sets none. |
use, x5c, … | none | deriveJWKFromPassword. Metadata merged onto the JWK. |
toJWK | false | deriveKeyFromPassword. Return a JWK instead of a CryptoKey. |
extractable | false | deriveKeyFromPassword. 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:
wrapKeywithPBES2-*, wherep2sandp2care required.