← 中文资源

简体中文版本

PBKDF2 用 WebCrypto 派生密钥

用 WebCrypto 的 PBKDF2 把口令拉伸成 256 位密钥:固定盐值加十万次迭代,派生结果确定可复现,最终以十六进制展示。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

derived bytes: 32
key hex: 7ed385456f6b11fe381b82d34e9384476dfbc84764f4d306ff62dc74846615a4

实现说明

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);