Hash-based Message Authentication Code (HMAC) is a kind of message authentication code based on hash function, mainly used to verify data integrity and identity authentication.
In this example, an Edge Function is used the Web Crypto API
to implement HMAC signing and signature verification.
async function getMac(message, key) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
return await crypto.subtle.sign('HMAC', key, data);
}
async function verifyMac(message, key, mac) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
return await crypto.subtle.verify('HMAC', key, mac, data);
}
async function generateKey() {
return await crypto.subtle.generateKey(
{
name: 'HMAC',
hash: 'SHA-256',
},
true,
['sign', 'verify'],
);
}
async function handleRequest() {
const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.';
const key = await generateKey();
const mac = await getMac(text, key);
const result = await verifyMac(text, key, mac);
return new Response(JSON.stringify({ result }));
}
addEventListener('fetch', event => {
event.respondWith(handleRequest());
});