An HMAC tag and an HKDF key
Authenticate a message with HMAC, check a tag in constant time, derive a key with HKDF.
Apache-2.0Runs on this page
Package: @awacloud/fw
Authenticate a message with HMAC-SHA256, check a received tag in constant time, and derive a 256-bit key with HKDF, in pure JavaScript.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
Signed webhooks, tamper-evident cookies or tokens (a tag), and a key derived
from a shared secret or a password hash for one purpose (HKDF's info).
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link.
What it shows
new hmac.fn(key).mac(message)for a tag;hmac.verify(key, message, tag)checks a received tag in constant time (never with===), and input that is not hex is rejected before it.hkdf.derive(salt, ikm, info, bits): extract-then-expand in one call. The page'sderiveKeykeeps that argument order, so a copy cannot swap the salt and the keying material.- The primitives return bit arrays:
bitArrayconverts to bytes,hexdisplays them.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { hmac } from '@awacloud/fw/crypto/hash/hmac.js';
import { hkdf } from '@awacloud/fw/crypto/hash/hkdf.js';
import { hex } from '@awacloud/fw/io/codec/hex.js';
fw.runtime.registerAllDeep([hmac, hkdf, hex]);
const HMAC = fw.runtime.resolve('hmac');
const HKDF = fw.runtime.resolve('hkdf');
const HEX = fw.runtime.resolve('hex');
// The primitives speak bit arrays (32-bit words): bitArray converts at the edges.
const BA = fw.runtime.resolve('bitArray');
/** HMAC-SHA256 tag of a message under a key, in hex. @param {string} key @param {string} message */
export const tag = (key, message) => HEX.fromBytes(BA.ba_to_ui8(new HMAC.fn(key).mac(message)));
/**
* Constant-time check of a received tag: never compare tags with `===`.
* @param {string} key @param {string} message @param {string} hexTag
* @returns {boolean}
*/
export function verifyTag(key, message, hexTag) {
if (!/^([0-9a-f]{2})+$/i.test(hexTag)) return false;
return HMAC.verify(key, message, BA.ui8_to_ba(HEX.toBytes(hexTag)));
}
/**
* HKDF-SHA256: extract a pseudorandom key from the input keying material (a
* shared secret, a password hash…), then expand `bits` of key bound to `info`.
* Same argument order as `hkdf.derive`, so a copy cannot swap them.
* @param {string} salt @param {string} ikm @param {string} info @param {number} [bits]
*/
export const deriveKey = (salt, ikm, info, bits = 256) => (
HEX.fromBytes(BA.ba_to_ui8(HKDF.derive(salt, ikm, info, bits))));
/** @param {string} id */
const field = (id) => /** @type {HTMLInputElement} */ (document.getElementById(id));
/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };
function update() {
const [key, message] = [field('key').value, field('message').value];
show('hmac', tag(key, message));
const received = field('received').value.trim();
show('check', received ? (verifyTag(key, message, received) ? 'valid' : 'NOT valid') : 'paste a tag to check it');
show('hkdf', deriveKey('examples', message, 'aead-key'));
}
for (const id of ['key', 'message', 'received']) field(id).addEventListener('input', update);
update();index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · An HMAC tag and an HKDF key</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>An HMAC tag and an HKDF key</h1>
<label for="message">Message</label>
<input id="message" type="text" value="The quick brown fox jumps over the lazy dog" autocomplete="off">
<label for="key">HMAC key</label>
<input id="key" type="text" value="key" autocomplete="off">
<dl>
<dt>HMAC-SHA256 tag</dt><dd><code id="hmac"></code></dd>
</dl>
<label for="received">A tag you received (hex)</label>
<input id="received" type="text" autocomplete="off" spellcheck="false">
<p>Check: <output id="check" for="received"></output></p>
<dl>
<dt>HKDF-SHA256 key from the message (salt "examples", info "aead-key", 256 bits)</dt>
<dd><code id="hkdf"></code></dd>
</dl>
</main>
</body>
</html>