function uint8ArrayToHex(uint8Array) {
return Array.prototype.map.call(uint8Array, x => ('0' + x.toString(16)).slice(-2)).join('');
}
async function generateHmac({ secretKey, message, hash }) {
const encoder = new TextEncoder();
const secretKeyBytes = encoder.encode(secretKey);
const messageBytes = encoder.encode(message);
const key = await crypto.subtle.importKey('raw', secretKeyBytes, { name: 'HMAC', hash }, false, ['sign']);
const signature = await crypto.subtle.sign('HMAC', key, messageBytes);
const signatureArray = new Uint8Array(signature);
return uint8ArrayToHex(signatureArray);
}
async function handleRequest(request) {
const secretKey = 'YOUR_SECRET_KEY';
const message = 'YOUR_MESSAGE';
const hmac = await generateHmac({ secretKey, message, hash: 'SHA-256' });
request.headers.set('Authorization', `HMAC-SHA256 ${hmac}`);
return fetch(request);
}
addEventListener('fetch', event => {
event.passThroughOnException();
event.respondWith(handleRequest(event.request));
});
Was this page helpful?