KITFORMA · EDITORIAL ANSWER
How do I compare webhook signatures without ordinary string equality?
KitForma editorial guide. A signature verifier should compare validated, equal-length byte sequences with an appropriate constant-time primitive. Ordinary string comparison is not designed for that purpose.
Step-by-step answer
import assert from 'node:assert/strict';
import { createHmac, timingSafeEqual } from 'node:crypto';
const payload = Buffer.from('{"event":"test"}');
const expected = createHmac('sha256', 'test-key-not-a-secret').update(payload).digest();
function matches(hex) {
if (!/^[0-9a-f]{64}$/i.test(hex)) return false;
const candidate = Buffer.from(hex, 'hex');
return candidate.length === expected.length && timingSafeEqual(candidate, expected);
}
assert.equal(matches(expected.toString('hex')), true);
assert.equal(matches('00'), false);
assert.equal(matches('00'.repeat(32)), false);Sources and verification
Sources checked:
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.