HMAC 数字签名

最近更新时间:2023-11-21 14:07:51

我的收藏
HMAC(Hash-based Message Authentication Code)是一种基于哈希函数的消息认证码,主要用于验证数据的完整性和身份认证。该示例使用 Web Crypto API实现 HMAC-SHA256 签名,并将签名信息存入请求头,配合源站实现数据完整性校验或身份认证,开发者可根据需要修改代码。
注意
该示例要求与源站配合使用,即源站需要具备对应的签名校验算法。
现网使用该示例提供的代码,需要按照注释修改代码。

示例代码

function uint8ArrayToHex(uint8Array) {
return Array.prototype.map.call(uint8Array, x => ('0' + x.toString(16)).slice(-2)).join('');
}

async function generateHmac({ secretKey, message, hash }) {
const encoder = new TextEncoder();
const secretKeyBytes = encoder.encode(secretKey);
const messageBytes = encoder.encode(message);
const key = await crypto.subtle.importKey('raw', secretKeyBytes, { name: 'HMAC', hash }, false, ['sign']);

const signature = await crypto.subtle.sign('HMAC', key, messageBytes);
const signatureArray = new Uint8Array(signature);
return uint8ArrayToHex(signatureArray);
}

async function handleRequest(request) {
const secretKey = 'YOUR_SECRET_KEY';
// 使用时请修改为需要被签名的信息,一般为多个数据的组合,例如:时间戳+请求相关信息等
const message = 'YOUR_MESSAGE';
// hash 取 SHA-1、SHA-256、SHA-384、SHA-512 之一
const hmac = await generateHmac({ secretKey, message, hash: 'SHA-256' });
request.headers.set('Authorization', `HMAC-SHA256 ${hmac}`);

return fetch(request);
}
addEventListener('fetch', event => {
event.passThroughOnException();
event.respondWith(handleRequest(event.request));
});


示例预览

在 PC 端与移动端的浏览器地址栏中输入匹配到边缘函数触发规则的 URL(如:https://example.com/hmac),即可预览到示例效果。
身份校验未通过。

身份校验通过。


相关参考