HMAC

January 24, 2019 ยท View on GitHub

W3 specification

Operations

OperationParametersResult
generateKeyHmacKeyGenParamsCryptoKey
importKeyHmacImportParamsCryptoKey
exportKeyNoneJsonWebKey or BufferSource
signNoneArrayBuffer
verifyNoneBoolean

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
);