mdoTomofumi Chiba
3/29/2023, 9:40:15 AM

Deno で HMAC-SHA256

import { encode } from "https://deno.land/[email protected]/encoding/hex.ts";

async function sign(data: string, key: string) {
  const encoder = new TextEncoder();
  const keyBuf = encoder.encode(key);

  const cryptoKey = await crypto.subtle.importKey(
    "raw",
    keyBuf,
    { name: "HMAC", hash: "SHA-256" },
    true,
    ["sign", "verify"],
  );

  const unit8Array = encoder.encode(data);
  const result = await crypto.subtle.sign("HMAC", cryptoKey, unit8Array.buffer);
  return new TextDecoder().decode(encode(new Uint8Array(result)));
}

console.log(await sign("value", "secret_key"));

以下のコマンドラインと同じ

echo -n "value" | openssl dgst -sha256 -hmac "secret_key"
TweetLike