Learn more about Russian war crimes in Ukraine.

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:

Signature:

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

function buf2hex(buf) {
  return Array.prototype.map.call(new 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(
  {name:"HMAC","hash":"SHA-256"},
  true,
  ["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(
  "jwk",
  jwk,
  {name:"HMAC","hash":"SHA-256"},
  true,
  ["sign", "verify"]);

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

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.