UNPKG

1.11 kBJavaScriptView Raw
1/**
2 * Constant-Time Buffer Compare
3 * ============================
4 *
5 * A constant-time comparison function. This should be used in any security
6 * sensitive code where leaking timing information may lead to lessened
7 * security. Note that if the buffers are not equal in length, this function
8 * loops for the longest buffer, which may not be necessary. Usually this
9 * function should be used for buffers that would otherwise be equal length,
10 * such as a hash, particularly Hmacs.
11 *
12 * The algorithm here, which is XORs each byte (or, if undefined, 0) with the
13 * corresponding other byte, and then ORs that with a running total (d), is
14 * adapted from here:
15 *
16 * https://groups.google.com/forum/#!topic/keyczar-discuss/VXHsoJSLKhM
17 */
18'use strict'
19const cmp = (buf1, buf2) => {
20 if (!Buffer.isBuffer(buf1) || !Buffer.isBuffer(buf2)) {
21 throw new Error('buf1 and buf2 must be buffers')
22 }
23 if (buf1.length !== buf2.length) {
24 return false
25 }
26
27 let d = 0
28 for (let i = 0; i < buf1.length; i++) {
29 const x = buf1[i]
30 const y = buf2[i]
31 d |= x ^ y
32 }
33
34 return d === 0
35}
36
37export { cmp }