javascript / expert
Snippet
Timing-Safe Secret Verification Using TypedArrays in Edge Middleware
Standard string equality checks (`===`) are vulnerable to timing side-channel attacks because string comparison exits early on the first mismatched character. By encoding incoming signatures and shared secrets into `Uint8Array` TypedArrays of identical length, `crypto.timingSafeEqual` enforces constant-time comparison in Next.js backend logic.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { timingSafeEqual } from 'crypto';export function verifyWebhookSignature(payload, signature, secret) {const encoder = new TextEncoder();const a = encoder.encode(signature);const b = encoder.encode(secret);if (a.byteLength !== b.byteLength) {return false;}return timingSafeEqual(a, b);}
nextjs
Breakdown
1
const a = encoder.encode(signature);
Converts string parameters into Uint8Array buffers suitable for byte-level cryptographic comparison.
2
return timingSafeEqual(a, b);
Executes constant-time byte comparison on two TypedArrays to prevent timing side-channel attacks.