实现说明
await 标出每个异步边界——没有 fire-and-forget。
演示用的数据放在这几个模块级绑定中:key、jwk、revived、roundtrip。
使用要点
- 浏览器才是这里的运行环境:
crypto在 Node 里拿不到。 - 跑完文件,输出里会留下标记——
kty:、same material:、usages:。
常见问题
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 状态都挂在模块顶层:key、jwk、revived。
核心语句
const roundtrip = await crypto.subtle.exportKey('jwk', revived);
const jwk = await crypto.subtle.exportKey('jwk', key);
const revived = await crypto.subtle.importKey(
'jwk',
jwk,
'AES-GCM',
true,
['encrypt', 'decrypt'],
);
代码示例
// WebCrypto key lifecycle: generate an extractable key, persist it as JWK,
// and rebuild it later without holding raw key bytes in application state.
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true, // extractable: required for exportKey
['encrypt', 'decrypt'],
);
const jwk = await crypto.subtle.exportKey('jwk', key);
console.log('kty:', jwk.kty, 'alg:', jwk.alg, 'k length:', jwk.k.length);
// Later: rebuild the same key from the stored JWK
const revived = await crypto.subtle.importKey(
'jwk',
jwk,
'AES-GCM',
true,
['encrypt', 'decrypt'],
);
const roundtrip = await crypto.subtle.exportKey('jwk', revived);
console.log('same material:', roundtrip.k === jwk.k);
console.log('usages:', revived.usages.join(','));