实现说明
真正干活的是函数 demonstrate,其余都是接线。
await 标出每个异步边界——没有 fire-and-forget。
使用要点
crypto只存在于浏览器——Node 运行时没有现成的垫片。- 跑完文件,输出里会留下标记——
signature bytes:、verify same payload:、verify tampered payload:。
常见问题
除了语言工具链还要下载什么吗?
除了这个语言的工具链,什么都不用再下载。 文件在加载时定义 demonstrate。
主要签名是 async function demonstrate(payload)
核心语句
const invalid = await crypto.subtle.verify('HMAC', key, signature, tampered);
const valid = await crypto.subtle.verify('HMAC', key, signature, data);
const signature = await crypto.subtle.sign('HMAC', key, data);
代码示例
// HMAC with the WebCrypto API: sign once, then verify without ever
// comparing secrets or signatures byte by byte.
const encoder = new TextEncoder();
async function demonstrate(payload) {
// Non-extractable key: the raw key material can never be read back out
const key = await crypto.subtle.generateKey(
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify'],
);
const data = encoder.encode(payload);
const signature = await crypto.subtle.sign('HMAC', key, data);
console.log('signature bytes:', signature.byteLength);
// verify() returns true for the same payload
const valid = await crypto.subtle.verify('HMAC', key, signature, data);
console.log('verify same payload:', valid);
// and false once the payload changes by even one byte
const tampered = encoder.encode(payload + ' ');
const invalid = await crypto.subtle.verify('HMAC', key, signature, tampered);
console.log('verify tampered payload:', invalid);
}
await demonstrate('webhook:order-42');