边缘开发者平台
  • 边缘函数
    • 概述
    • 快速指引
    • 操作指引
      • 函数管理
      • Web调试
      • 触发配置
      • 环境变量
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • 示例函数
      • 示例概述
      • 301重定向
      • 获取客户端URL信息
      • 基于客户端地理位置的自定义
      • 获取客户端地理位置信息
      • 批量重定向
      • 返回 HTML 页面
      • 返回 JSON
      • Fetch 远程资源
      • 请求头鉴权
      • 修改响应头
      • AB 测试
      • 设置 Cookie
      • 基于请求区域重定向
      • Cache API 使用
      • 缓存 POST 请求
      • 流式响应
      • 合并资源流式响应
      • 防篡改校验
      • m3u8 改写与鉴权
      • 图片自适应缩放
      • 图片自适应 WebP
      • 自定义 Referer 限制规则
      • 远程鉴权
      • HMAC 数字签名
      • 自定义下载文件名
      • 获取客户端 IP
    • 最佳实践
      • 通过边缘函数实现自适应图片格式转换
当前内容仅提供英语版本,中文版我们将尽快补充,感谢您的理解。

HMAC 数字签名

Hash-based Message Authentication Code (HMAC) is a kind of message authentication code based on hash function, mainly used to verify data integrity and identity authentication. Web Crypto API is used in this example to achieve HMAC-SHA256 signature and store the signature information in a request header. It achieves data integrity or identity authentication collaborating with origin server. Developers can modify the code based on their specific needs.
Note
Cooperation with the origin server is required in this example, which means that the origin server must possess the corresponding signature verification algorithm.
For live network use of the code provided in this example, modification must be made in accordance with the comments.

Sample code

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';
// Please modify the message to the information that needs to be signed, generally a combination of various data, such as timestamp and relevant request information.
const message = 'YOUR_MESSAGE';
// Choose one from SHA-1, SHA-256, SHA-384, and SHA-512 for hash.
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));
});


Sample Preview

Enter a URL (such as https://example.com/hmac) that matches the trigger rule of edge function in the address bar of a browser on both the PC and mobile terminal to preview the example effect.
Identity verification failed.

Identity verification succeeded.


Related References