HMAC 生成与验证
在 Github 上编辑
此示例演示如何使用 Deno 的内置 SubtleCrypto API 和 SHA-256 哈希函数生成和验证 HMAC(基于哈希的消息身份验证代码)。
定义 HMAC 的密钥(在实际应用中,安全地存储此密钥)
const secret = "supersecretkey";
使用 TextEncoder 将密钥转换为 Uint8Array
const encoder = new TextEncoder();
const keyData = encoder.encode(secret);
将密钥导入 SubtleCrypto API 以进行 HMAC 操作
const key = await crypto.subtle.importKey(
"raw", // The format of the key
keyData, // The key data
{ // Algorithm details
name: "HMAC",
hash: { name: "SHA-256" },
},
false, // Whether the key is extractable
["sign", "verify"], // Key usages: Sign and Verify
);
要验证的消息
const message = "Authenticate this message";
将消息转换为 Uint8Array
const messageData = encoder.encode(message);
为消息生成 HMAC 签名
const signature = await crypto.subtle.sign("HMAC", key, messageData);
将 ArrayBuffer 转换为十六进制字符串的函数,仅用于可读性。这不是生成或验证的一部分
function bufferToHex(buffer: ArrayBuffer): string {
const byteArray = new Uint8Array(buffer);
return Array.from(byteArray)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
以十六进制格式输出生成的 HMAC 签名
console.log("Generated HMAC:", bufferToHex(signature));
验证 HMAC 签名
const isValid = await crypto.subtle.verify("HMAC", key, signature, messageData);
输出验证结果
console.log("Is the HMAC valid?", isValid);
使用 Deno CLI 在本地运行 此示例
deno run https://docs.deno.org.cn/examples/scripts/hmac_generate_verify.ts