unixcrypt-browser
Version:
Node.js implementation of Unixcrypt, specifically SHA-256 and SHA-512
31 lines (28 loc) • 753 B
text/typescript
/**
* string, buffer comparison in length-constant time
* @see https://codahale.com/a-lesson-in-timing-attacks/
*
* @param {string} a - string from input
* @param {string} b - string to compare with `a`
* @return {boolean} true if strings match
*/
export function timingSafeEqual(a: string, b: string) {
if (!a || !a.length || !b || !b.length) {
return false
}
const _a = toArray(a)
const _b = toArray(b)
let diff = bton(_a.length !== _b.length)
for (let i = 0; i < _b.length; i++) {
diff |= bton(_a[i] !== _b[i])
}
return diff === 0
}
export default timingSafeEqual
/**
* 1=true 0=false
* @param {boolean} b
* @returns {number}
*/
const bton = (b: boolean) => (b ? 1 : 0)
const toArray = (s: string) => s.split('')