边缘安全加速平台 EO HMAC 数字签名

HMAC(Hash-based Message Authentication Code)是一种基于哈希函数的消息认证码,主要用于验证数据的完整性和身份认证。该示例使用 Web Crypto API实现 HMAC-SHA256 签名,并将签名信息存入请求头,配合源站实现数据完整性校验或身份认证,开发者可根据需要修改代码。

相关产品
边缘安全加速平台 EO 产品页,含版本规格、价格与购买入口。

一、示例代码

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),即可预览到示例效果。

·身份校验未通过。

·身份校验通过。

三、相关参考

·Runtime APIs: Fetch

·Runtime APIs: Web Crypto

·Runtime APIs: Headers

·Runtime APIs: Response

赞 (0)
上一篇 4天前
下一篇 4天前