PBKDF2 Derives Keys With WebCrypto
Stretch a password into a 256-bit key with WebCrypto PBKDF2 using a fixed salt and 100000 iterations, then render the derived bits as hex.
Code
// WebCrypto PBKDF2: stretch a password into a 256-bit key.
const password = 'correct horse battery staple';
const salt = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
const keyMaterial = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(password),
'PBKDF2',
false,
['deriveBits'],
);
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt, iterations: 100_000, hash: 'SHA-256' },
keyMaterial,
256,
);
const hex = [...new Uint8Array(bits)].map((b) => b.toString(16).padStart(2, '0')).join('');
console.log('derived bytes:', bits.byteLength);
console.log('key hex:', hex);Output
Captured from a sandboxed run of this snippet in the build pipeline.
derived bytes: 32
key hex: 7ed385456f6b11fe381b82d34e9384476dfbc84764f4d306ff62dc74846615a4How the snippet works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The whole flow works on the top-level bindings: password, salt, keyMaterial, bits.
Points of care
- No third-party code is loaded at any point while this runs.
- A browser is the runtime here:
cryptoare not available in Node.
Applying it
The demo output is labeled (derived bytes:, key hex:), so the printed lines read as a trace of the operations that ran.
Statements that matter
const hex = [...new Uint8Array(bits)].map((b) => b.toString(16).padStart(2, '0')).join('');
const keyMaterial = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(password),
'PBKDF2',
false,
['deriveBits'],
);
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt, iterations: 100_000, hash: 'SHA-256' },
keyMaterial,
256,
);
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `password`, `salt`, `keyMaterial`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.