HMAC Signing With crypto.subtle

Sign payloads with a non-extractable HMAC key from the WebCrypto API and verify with subtle.verify, so secrets never need byte-by-byte comparison.

JavascriptSecurity Boundaries

Code

javascriptsnippet
27 lines
// HMAC with the WebCrypto API: sign once, then verify without ever
// comparing secrets or signatures byte by byte.
const encoder = new TextEncoder();

async function demonstrate(payload) {
  // Non-extractable key: the raw key material can never be read back out
  const key = await crypto.subtle.generateKey(
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign', 'verify'],
  );

  const data = encoder.encode(payload);
  const signature = await crypto.subtle.sign('HMAC', key, data);
  console.log('signature bytes:', signature.byteLength);

  // verify() returns true for the same payload
  const valid = await crypto.subtle.verify('HMAC', key, signature, data);
  console.log('verify same payload:', valid);

  // and false once the payload changes by even one byte
  const tampered = encoder.encode(payload + ' ');
  const invalid = await crypto.subtle.verify('HMAC', key, signature, tampered);
  console.log('verify tampered payload:', invalid);
}

await demonstrate('webhook:order-42');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

signature bytes: 32
verify same payload: true
verify tampered payload: false

What the code does

Everything happens inside the function demonstrate.

Await points sequence the asynchronous work; a rejection lands at the awaiting line.

What to watch for

  • Everything it calls is documented as part of the language core.
  • The snippet leans on crypto — browser-only surfaces a bare Node process cannot provide.

Applying it

Entry signature: async function demonstrate(payload)

Output lines are prefixed (signature bytes:, verify same payload:, verify tampered payload:), making each step’s effect easy to spot.

Statements that decide the outcome

const invalid = await crypto.subtle.verify('HMAC', key, signature, tampered);
const valid = await crypto.subtle.verify('HMAC', key, signature, data);
const signature = await crypto.subtle.sign('HMAC', key, data);

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `demonstrate` at load time.