Signing a string with HMAC using the Web Crypto API

Below, you can type a plaintext string, and enter a secret key. It will print the signature resulting from signing the plaintext with your secret key.

String to sign:

Shared secret key:


This is implemented with the Web Cryptography API. Specifically, it uses window.crypto.subtle.sign("HMAC", CryptoKey, ArrayBuffer):

function buf2hex(buf) {
  return Uint8Array(buf), x=>(('00'+x.toString(16)).slice(-2))).join('');
async function hmacSha256(key, str) {
  const buf = new TextEncoder("utf-8").encode(str);
  const sig = await window.crypto.subtle.sign("HMAC", key, buf);
  return buf2hex(sig);

Your secret key is generated when this page loads. The key is in “JSON Web Key” format. It was generated with window.crypto.subtle.generateKey and exported with window.crypto.subtle.exportKey, like so:

const key = await window.crypto.subtle.generateKey(
  ["sign", "verify"]);
secretKeyEl.value = JSON.stringify(
  await window.crypto.subtle.exportKey("jwk", key));

You can edit your key in the textarea, or copy-paste a new one. The key is imported from the textarea with window.crypto.subtle.importKey:

const jwk = JSON.parse(secretKeyEl.value);
const key = await window.crypto.subtle.importKey(
  ["sign", "verify"]);
I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged #programming, #crypto, #javascript. All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.