DEV Community

Discussion on: Hash your passwords with scrypt using Nodejs crypto module

Collapse
 
bdougherty profile image
Brad Dougherty

It's probably best to use crypto.timingSafeEqual(a, b) to compare the keys in the verify function to protect against timing attacks.

Collapse
 
yashraj021 profile image
Yash

Hey Brad, I am new to authentication, can please explain gour point?

Collapse
 
bdougherty profile image
Brad Dougherty

The Wikipedia article explains it pretty well: en.wikipedia.org/wiki/Timing_attack

In other words, the verify function should look something like this:

import crypto from 'crypto';
import { promisify } from 'util';

const scrypt = promisify(crypto.scrypt);

async function verify(password, hash) {
    const [salt, key] = hash.split(":")
    const keyBuffer = Buffer.from(key, 'hex')
    const derivedKey = await scrypt(password, salt, 64)
    return crypto.timingSafeEqual(keyBuffer, derivedKey)
}
Enter fullscreen mode Exit fullscreen mode

The key has to be converted into a buffer because crypto.timingSafeEqual only accepts buffers for the arguments.

Doing it this way means that the comparison operation takes the same amount of time every single time.