How to Encrypt User Data With Passkeys Using the WebAuthn PRF Extension
· 36 min read
In my last article, I explained why a passkey is more than a nicer way to sign in. Through a WebAuthn extension called PRF, a passkey can produce a stable 32-byte secret that only the user can unlock, on any device the passkey has synced to. That article covered the why and the lessons from shipping it. This one is the how.
We'll build end-to-end encryption that unlocks with a passkey, works on a brand-new phone without any extra setup, and leaves your server holding nothing it can read. Along the way, we'll add a recovery password for users whose passkey provider doesn't support PRF yet, because some of your users will be in that position from day one.
Every decision in this guide comes back to five requirements, so it's worth checking your own changes against them as you adapt the code:
- The server never sees a usable key. It only stores encrypted material and metadata that isn't secret.
- Any of the user's devices can unlock. If their passkey has synced to a new phone, that alone should be enough.
- Many unlock methods, one data key. Adding or removing a passkey should never mean re-encrypting the user's data.
- Nobody gets stuck. Every user can set up and unlock, including people whose passkey provider doesn't support PRF.
- Unlocked keys stay in memory. Key material is never written to disk on the device.
To follow along, you'll need:
- A site served over HTTPS.
localhost works for development.
- Some comfort with
async/await and typed arrays in JavaScript.
- A backend that can store and return a few JSON records per user. The examples call a simple REST API with
fetch, but any backend works.
hash-wasm for Argon2id, which the recovery password needs. Everything else uses the browser's built-in WebAuthn and Web Crypto APIs.
The code is plain JavaScript and doesn't depend on a framework. Names like example-app are placeholders. Choose your own, and once you ship, never change them. Step 1 explains why.
PRF, defined in the WebAuthn Level 3 specification, lets a passkey compute HMAC-SHA-256 over an input you choose, using a secret that never leaves the authenticator. Before writing any code, it's worth knowing what happens between your call and the 32 bytes you get back, because it explains a few behaviours that would otherwise look like bugs.
When you ask for a PRF output, four things happen:
- Your code passes one or two inputs, called
first and second, in the prf extension of a WebAuthn call.
- The browser doesn't forward them as they are. It hashes each one together with a fixed label, the string "WebAuthn PRF" followed by a zero byte, so the values a website asks for can never collide with values other software derives from the same authenticator. That's why a website can't use PRF to reproduce a secret that, for example, a native disk-encryption tool derives from the same security key.
- The authenticator runs the CTAP2
hmac-secret extension. It computes HMAC-SHA-256 with a per-credential secret it generated when the passkey was created. That secret is separate from the passkey's signing key, and it's never exported.
- The browser hands the 32-byte result back to your code as an
ArrayBuffer.
Two things follow from this. The output is tied to one specific credential, so two different passkeys give you different outputs for the same input. And because the per-credential secret syncs along with the passkey, a synced passkey gives you the same output on every device.
Here's what the extension looks like inside a create() or get() call, and where the result shows up afterwards:
extensions: {
prf: {
eval: { first: inputA, second: inputB },
},
}
const { prf } = credential.getClientExtensionResults();
prf.enabled
prf.results.first
prf.results.second
In get(), you can also use evalByCredential, a map from base64url credential IDs to inputs. It lets you send a different input to each passkey in allowCredentials, which you'll need if you decide to store a random input per passkey instead of using one constant.
At registration, prf.enabled tells you whether the new credential supports PRF. Whether prf.results is filled in as well depends on the authenticator. Synced passkeys from Apple and Google can return the first output during create(), but many security keys can't and only produce output during get(). Your registration code has to handle both cases, and the one in step 2 does.
Asking for first and second in the same call gives you two independent secrets for a single biometric prompt. The main reason you'd want that is rotation: you evaluate the old input and the new input together, unwrap with the old key and re-wrap with the new one. Yubico's developer guide recommends this pattern of deriving two different secrets in a single user authentication event, and step 8 shows it in code.
Don't encrypt user data directly with a key derived from a passkey. Encrypt it with a random data key instead, and use each passkey only to lock and unlock that data key. This two-layer design is called envelope encryption, or key wrapping, and it's what keeps the system manageable once users have more than one way to unlock.
There are three kinds of key, and each has one job:
| Key |
Made from |
Lifetime |
Job |
| PRF output |
The passkey, on demand |
Seconds; discarded after use |
Raw material for a wrapping key |
| Wrapping key (key-encryption key) |
HKDF over the PRF output, or Argon2id over a password |
Seconds; non-extractable |
Encrypts and decrypts one wrapped copy of the data key |
| Data key (data-encryption key) |
32 random bytes, generated once |
The life of the account |
Encrypts the user's data, or a further key such as a messaging private key |
Each unlock method gets its own wrapping key and its own wrapped copy of the same data key:
Each unlock method wraps its own copy of the same data key.
Any one of those copies unwraps the same data key, and only the data key ever touches the user's data.
Why go to the trouble of two layers? Because users collect passkeys over time: one on a laptop, one on a phone, a security key in a drawer. With a single layer, adding a passkey would mean re-encrypting all of their data. With wrapping, it means encrypting 32 bytes one more time. Removing a passkey means deleting a row, and a recovery password is just another wrapper.
The server's job is small on purpose. It stores wrapper records, returns them to the signed-in owner, and never tries to interpret them.
Each unlock method is stored as one record:
| Field |
Type |
Example |
Notes |
id |
UUID |
3f2a… |
Generated by the client, so it can be referenced before the write returns |
userId |
ID |
|
The owner; every query filters on it |
method |
enum |
passkey-prf or password-argon2id |
Tells the client which unlock flow to run |
credentialId |
base64url |
|
Passkey wrappers only; not secret |
prfInputVersion |
string |
v1 |
Which PRF input produced this wrapper |
kdfParams |
JSON |
{ salt, t: 3, m: 65536, p: 1 } |
Password wrappers only; not secret |
wrappedKey |
base64url |
|
IV + ciphertext + tag; useless without the unlock method |
keyVersion |
integer |
1 |
Which data key this wraps; useful for future rotation |
label |
string |
iPhone |
Human-readable, shown in settings |
createdAt, lastUsedAt |
timestamp |
|
Lets users spot and remove methods they no longer use |
You only need four endpoints:
| Method and path |
Returns |
Notes |
GET /key-wrappers |
All wrappers without wrappedKey |
Drives the unlock screen. An empty list means the user hasn't enrolled. |
GET /key-wrappers/:id |
One wrapper with wrappedKey |
Called only after the user has proven they hold the matching passkey, or has typed a password. |
PUT /key-wrappers/:id |
The stored record |
Creates or replaces. It's idempotent, because the client chose the ID. |
DELETE /key-wrappers/:id |
Nothing |
Refuses to delete the last remaining wrapper. |
Three rules on the server matter more than they look:
- Keep the blobs out of the list. The list endpoint drives the unlock screen, so it gets called a lot. If it returned
wrappedKey, every session would receive a full set of material to attack offline without having proven anything.
- Rate-limit downloads of password wrappers. Someone who downloads a password wrapper can try guesses against it offline, so treat each download like a login attempt.
- Refuse to delete the last wrapper. Deleting it permanently removes the user's ability to unlock. If they want to swap methods, the client should add the new one first.
Protect every endpoint with your normal session authentication. The wrappers aren't secret, but the list shows which devices a user owns, and nobody else needs that information.
Before showing any setup screen, you need to know which path the user is likely to take. You'll also need a few small byte helpers, which are easiest to keep in one module.
export async function passkeyEncryptionAvailable() {
if (!window.isSecureContext) return false;
if (!window.PublicKeyCredential) return false;
if (PublicKeyCredential.getClientCapabilities) {
const caps = await PublicKeyCredential.getClientCapabilities();
if (caps['extension:prf'] === false) return false;
}
return true;
}
A true here means it's worth trying, not that it will work. The browser can support PRF while the passkey provider the user picks doesn't, and you only find that out from prf.enabled after registration. So design the flow to drop cleanly into the password path when that "no" arrives late.
WebAuthn and Web Crypto work with ArrayBuffers, while your API works with JSON. Base64url is the usual bridge between them, since it's URL-safe and it's how credential IDs are normally encoded.
export function toBase64url(bytes) {
const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
let bin = '';
for (const b of arr) bin += String.fromCharCode(b);
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function fromBase64url(str) {
const b64 = str.replace(/-/g, '+').replace(/_/g, '/');
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
return Uint8Array.from(atob(padded), c => c.charCodeAt(0));
}
export function concat(...parts) {
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
let offset = 0;
for (const p of parts) { out.set(p, offset); offset += p.length; }
return out;
}
export function bytesEqual(a, b) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
return diff === 0;
}
bytesEqual checks every byte instead of returning at the first difference. Credential IDs aren't secret, so timing doesn't matter here, but it's a good habit for any comparison in security code.
The examples in this guide also throw a few small custom errors, such as PrfUnsupportedError and WrongPasskeyError. Define them however your codebase handles errors. The error reference near the end lists what each one means.
export const PRF_INPUT = new TextEncoder().encode('example-app:e2e-wrap:v1');
export const HKDF_INFO = new TextEncoder().encode('example-app:wrapping-key:v1');
These two values are part of your storage format. If you change either one, every wrapper you've already stored becomes impossible to decrypt. Put a version in them, write a test that fails if they change, and when you need new values, add a v2 next to v1 instead of editing a version you've already released.
Registration creates the passkey and gets its PRF output. If the authenticator doesn't return the output during create(), we ask for it with a second prompt.
const WEBAUTHN_TIMEOUT_MS = 60_000;
export async function registerPasskeyWithPrf({
userHandle,
userName,
displayName,
excludeCredentialIds = [],
}) {
const credential = await withTimeout(
navigator.credentials.create({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rp: { name: 'Example App', id: location.hostname },
user: { id: userHandle, name: userName, displayName },
pubKeyCredParams: [
{ type: 'public-key', alg: -7 },
{ type: 'public-key', alg: -257 },
],
authenticatorSelection: {
residentKey: 'required',
userVerification: 'required',
},
excludeCredentials: excludeCredentialIds.map(id => ({ type: 'public-key', id })),
timeout: WEBAUTHN_TIMEOUT_MS,
extensions: { prf: { eval: { first: PRF_INPUT } } },
},
}),
);
const prf = credential.getClientExtensionResults().prf;
if (!prf?.enabled) throw new PrfUnsupportedError();
let prfOutput = prf.results?.first;
if (!prfOutput) {
prfOutput = await evaluatePrf([credential.rawId]);
}
return { credentialId: new Uint8Array(credential.rawId), prfOutput };
}
When results.first comes back empty, we evaluate PRF with a normal get() call that's limited to the credential we just created:
export async function evaluatePrf(credentialIds) {
const assertion = await withTimeout(
navigator.credentials.get({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rpId: location.hostname,
allowCredentials: credentialIds.map(id => ({ type: 'public-key', id })),
userVerification: 'required',
timeout: WEBAUTHN_TIMEOUT_MS,
extensions: { prf: { eval: { first: PRF_INPUT } } },
},
}),
);
const out = assertion.getClientExtensionResults().prf?.results?.first;
if (!out) throw new PrfUnsupportedError();
return out;
}
function withTimeout(promise, ms = WEBAUTHN_TIMEOUT_MS + 5_000) {
let timer;
return Promise.race([
promise.finally(() => clearTimeout(timer)),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error('WEBAUTHN_TIMEOUT')), ms);
}),
]);
}
A few options in these two functions are doing more than they look:
userVerification: 'required'. Without it, anyone holding an unlocked device could produce the PRF output, and your encryption would only be as strong as the device's screen-lock timeout. Requiring the biometric or PIN on every evaluation closes that gap.
residentKey: 'required'. This creates a discoverable credential, the kind that syncs through platform password managers and shows up in the browser's account picker. Non-discoverable credentials often don't sync, which breaks the second requirement.
excludeCredentials. The CTAP2 specification tells an authenticator to overwrite an existing discoverable credential when a new one is created with the same relying party ID and user handle. If that happens to a passkey you've already wrapped the data key for, the replacement has a different PRF secret, and the old wrapper can never be unlocked again. Passing the credential IDs you already have makes the browser refuse with InvalidStateError instead. During first-time enrolment the list is empty, and step 8 shows where it gets filled.
A stable, recognisable user handle and name. user.id should be an opaque identifier that stays the same for the account, and every passkey the user registers should use it. user.name is what password managers display, so use the email or username the person would recognise. A generic value like "user" makes their passkeys impossible to tell apart.
The challenge. If this passkey is only used to derive encryption keys, the challenge doesn't need to be verified on the server. Nobody is being authenticated here, and the user's existing session already proves who they are to your API. If the same passkey also signs the user in, generate the challenge on the server and verify the assertion there, the same way you would for passkey sign-in. Keep those two uses clearly separate in your code.
Your own timeout. The timeout option is only a hint, and the platform may ignore it. Racing the call against your own timer means the interface can always recover and offer the password path.
The second prompt. When results.first is missing, the user sees a second biometric prompt right after the first one. Tell them before the first prompt appears, with something like "You may be asked to confirm twice."
The PRF output is key material, not a key you should use directly. We'll run it through HKDF to produce an AES-256-GCM key for one stated purpose, and then let the raw bytes go.
export async function deriveWrappingKey(prfOutput) {
const ikm = await crypto.subtle.importKey(
'raw', prfOutput, 'HKDF', false, ['deriveKey'],
);
return crypto.subtle.deriveKey(
{ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: HKDF_INFO },
ikm,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
}
The PRF output is already 32 uniformly random bytes, so you might be wondering why this step is needed at all. There are three reasons:
- Domain separation. The
info label ties the derived key to one purpose. If you later need a second key from the same passkey, say for signing or for a different feature, you derive it with a different label and the two can never collide. Yubico's guide describes the info parameter as crucial for exactly this reason.
- The right key type.
deriveKey gives you a CryptoKey that only works with AES-GCM and only for the operations you list. Passing raw bytes around makes it easier to misuse them somewhere else in the codebase.
- Non-extractability. Once the wrapping key is derived, no script on the page can export, log or serialise it. The raw PRF output should go out of scope as soon as this function returns.
An empty salt is fine here because the input already has full entropy. HKDF's salt is there to strengthen weak inputs, so if your input ever comes from somewhere less random, revisit that choice.
Now we can create the data key, wrap it with the wrapping key and store the wrapper. The user only counts as enrolled once that wrapper is saved.
export async function wrapKey(dataKeyBytes, wrappingKey) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = new Uint8Array(
await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, wrappingKey, dataKeyBytes),
);
return toBase64url(concat(iv, ct));
}
export async function unwrapKey(wrapped, wrappingKey) {
const blob = fromBase64url(wrapped);
const iv = blob.slice(0, 12);
const ct = blob.slice(12);
return new Uint8Array(
await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, wrappingKey, ct),
);
}
AES-GCM is authenticated encryption. The 16-byte tag at the end of the ciphertext proves it hasn't been changed and that the right key was used, so a wrong passkey fails with an exception instead of quietly producing garbage. That exception is how step 5 knows the user picked the wrong passkey.
Use a fresh random IV for every wrap. Reusing an IV with the same AES-GCM key breaks both confidentiality and integrity. With a random 96-bit IV and only a handful of wraps per key, a collision isn't a realistic concern.
export async function enrollWithPasskey(user) {
const existing = await api.listWrappers();
if (existing.length > 0) throw new AlreadyEnrolledError();
const { credentialId, prfOutput } = await registerPasskeyWithPrf({
userHandle: user.handleBytes,
userName: user.email,
displayName: user.name,
});
const dataKeyBytes = crypto.getRandomValues(new Uint8Array(32));
const wrappingKey = await deriveWrappingKey(prfOutput);
await api.putWrapper(crypto.randomUUID(), {
method: 'passkey-prf',
credentialId: toBase64url(credentialId),
prfInputVersion: 'v1',
wrappedKey: await wrapKey(dataKeyBytes, wrappingKey),
keyVersion: 1,
label: suggestDeviceLabel(),
});
await keyStore.load(dataKeyBytes);
dataKeyBytes.fill(0);
}
The first check in this function is the most important line in the guide. If a user who's already enrolled ever reaches it, perhaps on a new device where nothing is cached, they silently get a second data key. Data encrypted under one key can't be read on a device that holds the other, and to the user it looks like random corruption. Anyone who already has wrappers should always be sent to unlock instead.
The order of operations matters too. The wrapper is stored before the key is used for anything, so a failed write can never leave the user with data encrypted under a key nothing can unlock. If your app also publishes a public key derived from this material, for messaging for example, and the user abandons setup before a wrapper is saved, revoke that public key so nobody encrypts to it.
dataKeyBytes.fill(0) is extra protection rather than a guarantee. JavaScript doesn't promise that every copy of the bytes is erased, but clearing the buffer you control shortens the time raw key bytes sit in memory.
For suggestDeviceLabel(), prefer something a person recognises, like "MacBook", "iPhone" or a name they type, over navigator.platform, which reports "MacIntel" even on Apple Silicon Macs.
Unlocking is enrolment in reverse. You find out which passkey the user has, get its PRF output, fetch the matching wrapper and unwrap it.
We'll split this into two functions. unlockWithPasskey() decides which path the user takes and loads the key, while unwrapWithPasskey() does the actual unwrapping and returns the raw data key bytes. Keeping them apart matters in step 8, where we need the raw bytes without loading anything.
export async function unlockWithPasskey() {
const wrappers = await api.listWrappers();
if (wrappers.length === 0) return 'enroll';
const passkeyWrappers = wrappers.filter(w => w.method === 'passkey-prf');
if (passkeyWrappers.length === 0) return 'password';
const dataKeyBytes = await unwrapWithPasskey(passkeyWrappers);
await keyStore.load(dataKeyBytes);
dataKeyBytes.fill(0);
return 'done';
}
export async function unwrapWithPasskey(passkeyWrappers) {
const assertion = await getAssertionWithRetry(
passkeyWrappers.map(w => fromBase64url(w.credentialId)),
);
const answered = new Uint8Array(assertion.rawId);
const wrapper = passkeyWrappers.find(w =>
bytesEqual(answered, fromBase64url(w.credentialId)),
);
if (!wrapper) throw new UnknownPasskeyError();
const prfOutput = assertion.getClientExtensionResults().prf?.results?.first;
if (!prfOutput) throw new PrfUnsupportedError();
const { wrappedKey } = await api.getWrapper(wrapper.id);
const wrappingKey = await deriveWrappingKey(prfOutput);
let dataKeyBytes;
try {
dataKeyBytes = await unwrapKey(wrappedKey, wrappingKey);
} catch {
throw new WrongPasskeyError();
}
api.touchWrapper(wrapper.id);
return dataKeyBytes;
}
async function getAssertionWithRetry(credentialIds) {
const request = (allow) => withTimeout(navigator.credentials.get({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rpId: location.hostname,
allowCredentials: allow.map(id => ({ type: 'public-key', id })),
userVerification: 'required',
timeout: WEBAUTHN_TIMEOUT_MS,
extensions: { prf: { eval: { first: PRF_INPUT } } },
},
}));
try {
return await request(credentialIds);
} catch (err) {
if (err.name === 'NotAllowedError') throw err;
return await request([]);
}
}
Passing every known credential ID in allowCredentials keeps the browser's picker limited to passkeys that can actually unlock. If that request fails for any reason other than the user cancelling, the single retry with an empty list lets the browser offer any passkey for your site. That rescues cases like a credential ID stored in an unexpected encoding by an older version of your client. Never retry after NotAllowedError, though. That's the user saying no.
A user can have several passkey wrappers, and only the wrapper for the passkey that answered can unlock. Comparing rawId with the stored IDs tells you which wrapper to fetch. It also means you download exactly one blob, and only after the user has proven they hold the matching passkey, which keeps material for offline attacks off the network.
If you chose random per-passkey PRF inputs instead of one constant, replace eval with evalByCredential and map each base64url credential ID to its own input. Everything else stays the same.
Once unlocked, the data key lives in memory as a non-extractable CryptoKey, behind a small module that the rest of your app talks to. Nothing else in the app ever touches key bytes.
let dataKey = null;
export const keyStore = {
async load(rawBytes) {
dataKey = await crypto.subtle.importKey(
'raw', rawBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'],
);
},
isUnlocked: () => dataKey !== null,
async encrypt(plaintext, context) {
if (!dataKey) throw new LockedError();
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(context) },
dataKey,
new TextEncoder().encode(plaintext),
);
return toBase64url(concat(iv, new Uint8Array(ct)));
},
async decrypt(payload, context) {
if (!dataKey) throw new LockedError();
const blob = fromBase64url(payload);
const pt = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: blob.slice(0, 12), additionalData: new TextEncoder().encode(context) },
dataKey,
blob.slice(12),
);
return new TextDecoder().decode(pt);
},
clear() { dataKey = null; },
};
The context argument becomes AES-GCM additional authenticated data. It isn't encrypted, but it is checked, so decryption fails if it doesn't match what was used to encrypt. Pass something like note:${noteId}:v1. That stops a malicious server from swapping one encrypted record for another, for example moving an encrypted note into a different slot the user sees, because the context would no longer match.
Don't persist the data key to localStorage, sessionStorage or IndexedDB, even if you wrap it with something local first. Anything on disk can be reached by malware, by browser extensions with storage access, and by anyone who picks up the unlocked device. A key in memory disappears when the tab closes.
The trade-off is that users have to unlock again after a full page reload. With a passkey, that's one touch, which is what makes this design practical now. It's fine to cache state that isn't secret, such as "this user is enrolled" and their public keys, so a returning user sees "Unlock" instead of "Set up".
| Event |
What to do |
| Page load, user signed in, key not loaded |
Show the unlock screen before any encrypted content renders |
| Unlock succeeds |
keyStore.load(), then render |
| User signs out |
keyStore.clear(), then clear any decrypted content from your state |
| Session expires |
Same as sign-out |
| Account switch in the same tab |
Clear first, then unlock as the new user |
Make the unlock screen a gate. If users can dismiss it without unlocking, every component in your app has to handle a half-loaded state, and what the user ends up looking at is a screen of content they can't read. Keep the gate up until the key is loaded or the user signs out.
A recovery password is one more wrapper around the same data key. The only difference from a passkey wrapper is where the wrapping key comes from.
Passwords can be guessed, so deriving a key from one has to be deliberately slow and expensive. We'll use Argon2id, the memory-hard function standardised in RFC 9106. Its memory cost is what makes guessing at scale on GPUs and custom hardware expensive.
import { argon2id } from 'hash-wasm';
const ARGON2_PARAMS = { iterations: 3, memorySize: 65536, parallelism: 1 };
export async function derivePasswordWrappingKey(password, salt, params = ARGON2_PARAMS) {
const keyBytes = await argon2id({
password,
salt,
...params,
hashLength: 32,
outputType: 'binary',
});
const key = await crypto.subtle.importKey(
'raw', keyBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'],
);
keyBytes.fill(0);
return key;
}
export async function addPasswordWrapper(password, dataKeyBytes) {
const salt = crypto.getRandomValues(new Uint8Array(16));
const wrappingKey = await derivePasswordWrappingKey(password, salt);
await api.putWrapper(crypto.randomUUID(), {
method: 'password-argon2id',
kdfParams: {
salt: toBase64url(salt),
t: ARGON2_PARAMS.iterations,
m: ARGON2_PARAMS.memorySize,
p: ARGON2_PARAMS.parallelism,
},
wrappedKey: await wrapKey(dataKeyBytes, wrappingKey),
keyVersion: 1,
label: 'Recovery password',
});
}
export async function unwrapWithPassword(password, wrapperId) {
const { kdfParams, wrappedKey } = await api.getWrapper(wrapperId);
const wrappingKey = await derivePasswordWrappingKey(
password,
fromBase64url(kdfParams.salt),
{ iterations: kdfParams.t, memorySize: kdfParams.m, parallelism: kdfParams.p },
);
try {
return await unwrapKey(wrappedKey, wrappingKey);
} catch {
throw new WrongPasswordError();
}
}
addPasswordWrapper stores the salt and cost settings in kdfParams, and unwrapWithPassword reads them back from the wrapper instead of using the current defaults. That means you can raise the cost for new wrappers later without breaking the ones users already have.
addPasswordWrapper needs the raw data key bytes, but the key in keyStore is non-extractable, so you can't read it back out. There are two clean ways to get them:
- Create every wrapper during enrolment, while you still hold the raw bytes. In
enrollWithPasskey, call addPasswordWrapper(password, dataKeyBytes) right after the passkey wrapper is stored and before dataKeyBytes.fill(0). This is the simplest option: offer the passkey, then the recovery password, then discard the bytes.
- Unlock again when adding a method later. Ask the user to unlock with a method they already have.
unwrapWithPasskey() or unwrapWithPassword() gives you fresh raw bytes, which you wrap for the new method and then clear. Step 8 uses this pattern.
There's a tempting third option, which is to make the long-lived key extractable. Avoid it, because then any script on the page can read the key.
- Cost. 64 MiB of memory, 3 passes and 1 lane is a sensible starting point for browsers, including mid-range phones. Measure on the slowest device you support and aim for somewhere between half a second and a second.
- Run it in a Web Worker. Argon2 at this cost freezes the interface if it runs on the main thread.
- Password rules. Require at least 8 characters and encourage a passphrase. A downloaded wrapper can be attacked offline, so the strength of the password is the whole defence.
- Keep the password in the browser. Derivation happens on the device, and the server only ever sees the salt and the cost settings.
This is where envelope encryption pays off. Adding, removing and rotating unlock methods only touch wrapper records, never the user's data.
The user first unlocks with a method they already have. That gives you the raw data key bytes, which you wrap for the new passkey and then clear.
export async function addPasskey(user, unwrapWithExisting) {
const wrappers = await api.listWrappers();
const dataKeyBytes = await unwrapWithExisting();
try {
const { credentialId, prfOutput } = await registerPasskeyWithPrf({
userHandle: user.handleBytes,
userName: user.email,
displayName: user.name,
excludeCredentialIds: wrappers
.filter(w => w.method === 'passkey-prf')
.map(w => fromBase64url(w.credentialId)),
});
const wrappingKey = await deriveWrappingKey(prfOutput);
await api.putWrapper(crypto.randomUUID(), {
method: 'passkey-prf',
credentialId: toBase64url(credentialId),
prfInputVersion: 'v1',
wrappedKey: await wrapKey(dataKeyBytes, wrappingKey),
keyVersion: 1,
label: suggestDeviceLabel(),
});
} finally {
dataKeyBytes.fill(0);
}
}
Requiring an existing method here is what stops someone with a hijacked session, but no passkey, from adding a passkey of their own and reading the data. Notice that excludeCredentialIds now holds the user's current passkeys, so trying to register again on a provider that already has one fails with InvalidStateError instead of replacing it.
Delete the wrapper record, and have the server refuse if it's the last one. Then tell the user plainly that the passkey itself still exists in their password manager, where they can delete it too, but that it can no longer unlock their data. Your app can't directly delete a passkey from someone's password manager.
Suppose you need to move from v1 to v2. Because PRF accepts two inputs, you can do it with a single biometric prompt. In this snippet, wrapper is the full record from GET /key-wrappers/:id, and PRF_INPUT_V1 is the PRF_INPUT constant from step 1:
const assertion = await navigator.credentials.get({ publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rpId: location.hostname,
allowCredentials: [{ type: 'public-key', id: credentialId }],
userVerification: 'required',
extensions: { prf: { eval: { first: PRF_INPUT_V1, second: PRF_INPUT_V2 } } },
}});
const { first, second } = assertion.getClientExtensionResults().prf.results;
const dataKeyBytes = await unwrapKey(wrapper.wrappedKey, await deriveWrappingKey(first));
const newWrapped = await wrapKey(dataKeyBytes, await deriveWrappingKey(second));
await api.putWrapper(wrapper.id, { ...wrapper, prfInputVersion: 'v2', wrappedKey: newWrapped });
dataKeyBytes.fill(0);
Do this lazily, when each user next unlocks, rather than as one big migration, and keep reading v1 wrappers until none are left.
Rotating the data key itself, after a suspected compromise for example, is a much bigger job. Every piece of data has to be re-encrypted and every wrapper re-created. That's what the keyVersion field is for: store it on each encrypted record, keep the old key available for reading during the migration, and write new data with the new key. It's worth designing this before you need it, because the middle of an incident is a bad time to start.
Every failure should leave the user with one clear next step, which is usually the other unlock method. Map each error to what the user needs to do next, not to the stack trace.
| Signal |
Where |
Meaning |
Response |
NotAllowedError |
create(), get() |
The user cancelled, or the prompt timed out on the platform |
Treat it as a choice. Don't show an error toast; show the password option. |
InvalidStateError |
create() |
The authenticator already holds a passkey from excludeCredentials |
Offer to unlock with that passkey instead. |
SecurityError |
create(), get() |
The relying party ID doesn't match the page's domain |
A configuration bug in development. In production, the passkey belongs to another domain, so offer the password. |
prf.enabled is false |
After create() |
The passkey provider doesn't support PRF |
Explain it in one sentence and continue with the password path. |
results.first missing |
After get() |
The provider didn't evaluate PRF for this request |
Same as above. |
WEBAUTHN_TIMEOUT (yours) |
withTimeout |
The prompt never resolved |
Reset the button and offer the password. |
WrongPasskeyError / WrongPasswordError (yours) |
unwrapWithPasskey, unwrapWithPassword |
unwrapKey threw OperationError: wrong passkey or password, or a modified blob |
Say "That didn't work" and allow a retry or the other method. |
UnknownPasskeyError (yours) |
Step 5 |
A passkey answered that has no wrapper |
The user picked a sign-in-only passkey. Ask them to choose another one, or use the password. |
| Empty wrapper list |
Step 5 |
The user has never enrolled |
Send them to enrolment. |
AlreadyEnrolledError (yours) |
Step 4 |
Enrolment was attempted while wrappers exist |
Send them to unlock. Never generate a second data key. |
Log the error name and the step, but never key material, PRF output or passwords. Error rates per browser and platform are your earliest warning that a vendor update has changed how PRF behaves.
Automate the logic with virtual authenticators, then check it on real devices, because PRF still behaves differently from one provider to the next.
Chrome's DevTools Protocol can create software authenticators that behave like real ones. Its WebAuthn domain has an option to enable the PRF extension on a virtual authenticator, which is off by default. Here's how to set one up from Playwright:
const cdp = await page.context().newCDPSession(page);
await cdp.send('WebAuthn.enable');
const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', {
options: {
protocol: 'ctap2',
transport: 'internal',
hasResidentKey: true,
hasUserVerification: true,
isUserVerified: true,
hasPrf: true,
automaticPresenceSimulation: true,
},
});
Check the option names against the protocol version your Chrome build ships with. The DevTools WebAuthn tab is handy for poking around by hand, but in CI you'll want the protocol.
These are the cases worth automating:
- Enrol, reload and unlock: data written before the reload decrypts after it.
- Two passkeys, where either one can unlock.
- A wrong password fails with
WrongPasswordError and doesn't load a key.
- Enrolment refuses to run when wrappers already exist.
- The server refuses to delete the last wrapper.
- A provider without PRF (
hasPrf: false) drops cleanly into the password path.
- A test that fails if
PRF_INPUT or HKDF_INFO change.
Virtual authenticators can't reproduce vendor quirks. Before launch, run enrolment and unlock by hand on at least: Android with Google Password Manager; an iPhone on a current version of iOS; a Mac, with both Safari and Chrome; Windows 11 with Windows Hello after the February 2026 update; one hardware security key; and one third-party password manager your users like. Corbado's support matrix makes a good checklist, and it notes data-loss bugs in iOS 18.0 to 18.3 that are worth testing around.
Run through this list before launch. Each item guards against a failure I'd expect to show up in the first month if it were missing.
Cryptography
Key lifecycle
WebAuthn
Product
Operations
This design keeps the user's data safe from your servers, from database leaks and from phishing. It doesn't protect against a compromised browser on an unlocked device, and it still trusts the code you ship.
| Threat |
Protected? |
Why |
| Database leak or curious operator |
Yes |
The server only holds wrapped keys and ciphertext |
| Phishing site |
Yes |
Passkeys are bound to your relying party ID, so a look-alike domain can't request them |
| Offline attack on a passkey wrapper |
Yes |
The wrapping key comes from 32 unpredictable bytes, so there's nothing to guess |
| Offline attack on a password wrapper |
Partly |
It's as strong as the password, slowed down by Argon2id. Rate-limit downloads. |
| Record swapping by the server |
Yes |
Additional authenticated data binds each ciphertext to its context |
| Hijacked session without the passkey |
Yes |
Adding a method requires unlocking with an existing one |
| Malware or a malicious extension on an unlocked device |
No |
Code running in the page can use the key, even though it can't export it |
| Malicious JavaScript served by your own server |
No |
On the web, the server that stores the ciphertext also ships the code that encrypts it |
| User loses every method |
No, by design |
Nobody holds a recovery key, and that's the point |
The code-delivery limit is worth dwelling on because it's specific to the web. Passkeys remove the need to trust your storage, not your build and release pipeline. You can reduce that risk with a strict Content Security Policy, no third-party scripts on pages that handle keys, subresource integrity and careful dependency management, and for the highest-assurance cases, native apps.
If your app encrypts data for other users, as in messaging, there's one more gap. The server hands out public keys, and a malicious server could substitute its own. The standard defence is letting users compare key fingerprints, or safety numbers, through another channel. PRF protects the user's own key, but it doesn't solve key distribution.