express-basic-auth icon indicating copy to clipboard operation
express-basic-auth copied to clipboard

[Question] safeCompare function

Open manooi opened this issue 2 years ago • 0 comments

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: -

  1. Why does it use userInputLength intead of secretLength when allocating secretBuffer?
  2. Why does it use bitwise & instead of the logical &&?

Thanks

manooi avatar Dec 21 '23 03:12 manooi