HMAC Signature Constant Time Compare
Compute HMAC signatures and verify with constant-time comparison to prevent timing attacks on webhook authentication.
Code
export async function hmacSign(key,message,algo='SHA-256'){const enc=new TextEncoder();const keyObj=await crypto.subtle.importKey('raw',enc.encode(key),{name:'HMAC',hash:algo},false,['sign','verify']);const sig=await crypto.subtle.sign('HMAC',keyObj,enc.encode(message));return[...new Uint8Array(sig)].map(b=>b.toString(16).padStart(2,'0')).join('');}export function constantTimeEqual(a,b){if(a.length!==b.length)return false;let diff=0;for(let i=0;i<a.length;i++)diff|=a.charCodeAt(i)^b.charCodeAt(i);return diff===0;}How it works
Structurally, expect the functions hmacSign and constantTimeEqual and nothing else.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- The snippet leans on
crypto— browser-only surfaces a bare Node process cannot provide. - The guard
a.length!==b.lengthshort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
The main signature reads export async function hmacSign(key,message,algo='SHA-256')
The surface worth importing is hmacSign; the helpers around it are private to the snippet.
Interactive Tools for This Topic
JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.TOTP URI Builder & Code GeneratorBuild valid otpauth://totp QR provisioning URIs and compute RFC 6238 HMAC-SHA1, SHA-256, or SHA-512 verification codes locally using Web Crypto.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `hmacSign`, `constantTimeEqual` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.