实现说明
await 标出每个异步边界——没有 fire-and-forget。
password、salt、keyMaterial、bits 定义在模块顶层,中间不经过函数作用域。
使用要点
crypto只存在于浏览器——Node 运行时没有现成的垫片。- 直接运行文件,输出会带上标签,比如
derived bytes:、key hex:——输出的每一行都能指回产生它的那次调用。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 状态都挂在模块顶层:password、salt、keyMaterial。
核心语句
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,
);
代码示例
// 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);