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.

JavascriptAuth Jwt

Code

javascriptsnippet
21 lines
// 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: 7ed385456f6b11fe381b82d34e9384476dfbc84764f4d306ff62dc74846615a4

How 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: crypto are 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

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`.