Skip to content

Latest commit

 

History

History
73 lines (65 loc) · 1.63 KB

HMAC.md

File metadata and controls

73 lines (65 loc) · 1.63 KB

HMAC

W3 specification

Operations

Operation Parameters Result
generateKey HmacKeyGenParams CryptoKey
importKey HmacImportParams CryptoKey
exportKey None JsonWebKey or BufferSource
sign None ArrayBuffer
verify None Boolean

Generate key

const keys = await crypto.subtle.generateKey(
  {
    name: "HMAC",
    hash: "SHA-256", // SHA-1, SHA-256, SHA-384, or SHA-512
    length: 128,     // 128, 192, or 256
  },
  false,
  ["sign", "verify"],
);

Import key

const key = await crypto.subtle.importKey(
  "jwk",
  {
    alg: "HS256",
    ext: true,
    k: "AQIDBAUGBwgJAAECAwQFBg",
    key_ops: ["sign", "verify"],
    kty: "oct",
  },
  {
    name: "HMAC",
    hash: "SHA-256",
  },
  false,
  ["verify"],
);

Export key

const jwk = await crypto.subtle.exportKey(
  "jwk",
  key,
);

Sign

const signature = await crypto.subtle.sign(
  "HMAC",
  key,
  data,  // BufferSource
);

Verify

const ok = await crypto.subtle.verify(
  "HMAC",
  key,
  signature, // BufferSource
  data,      // BufferSource
);