Skip to content

Commit c001335

Browse files
committed
fix: use HMAC-based comparison in safeEqual to prevent length-based timing attacks
1 parent 4fef87d commit c001335

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

src/safe_equal.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
* @copyright Boring Node
66
*/
77

8-
import { timingSafeEqual } from 'node:crypto'
8+
import { timingSafeEqual, createHmac, randomBytes } from 'node:crypto'
9+
10+
const hmacKey = randomBytes(32)
911

1012
export function safeEqual(
1113
a: string | ArrayBuffer | SharedArrayBuffer | Uint8Array | Buffer,
@@ -14,9 +16,8 @@ export function safeEqual(
1416
const bufferA = typeof a === 'string' ? Buffer.from(a, 'utf8') : Buffer.from(a as ArrayBuffer)
1517
const bufferB = typeof b === 'string' ? Buffer.from(b, 'utf8') : Buffer.from(b as ArrayBuffer)
1618

17-
if (bufferA.length !== bufferB.length) {
18-
return false
19-
}
19+
const hmacA = createHmac('sha256', hmacKey).update(bufferA).digest()
20+
const hmacB = createHmac('sha256', hmacKey).update(bufferB).digest()
2021

21-
return timingSafeEqual(bufferA, bufferB)
22+
return timingSafeEqual(hmacA, hmacB)
2223
}

0 commit comments

Comments
 (0)