HMAC Signature Constant Time Compare

Compute HMAC signatures and verify with constant-time comparison to prevent timing attacks on webhook authentication.

JavascriptSecurity Boundaries

Code

javascriptsnippet
1 line
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.length short-circuits the flow with an early return when 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

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.