express-basic-auth
express-basic-auth copied to clipboard
[Question] safeCompare function
Hi,
I use this library to secure my NestJS Swagger endpoints, and it works great! I wanted to see how it works by digging around in the source code, and I found something that seemed odd to me.
function safeCompare(userInput, secret) {
const userInputLength = Buffer.byteLength(userInput)
const secretLength = Buffer.byteLength(secret)
const userInputBuffer = Buffer.alloc(userInputLength, 0, 'utf8')
userInputBuffer.write(userInput)
const secretBuffer = Buffer.alloc(userInputLength, 0, 'utf8') // Question 1
secretBuffer.write(secret)
return !!(timingSafeEqual(userInputBuffer, secretBuffer) & userInputLength === secretLength) // Question 2
}
Here're my questions: -
- Why does it use
userInputLengthintead ofsecretLengthwhen allocatingsecretBuffer? - Why does it use bitwise
&instead of the logical&&?
Thanks