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://deno-docs.dev.org.tw/examples/scripts/hmac_generate_verify.ts