0

I am new to Nodejs. I am confused Which One Should i choose
i get this code from - here
I dont have more knowledge about this stuff.
Help me for better Understanding

const crypto = require("crypto")

async function hash(password) {
    return new Promise((resolve, reject) => {
        const salt = crypto.randomBytes(8).toString("hex")

        crypto.scrypt(password, salt, 64, (err, derivedKey) => {
            if (err) reject(err);
            resolve(salt + ":" + derivedKey.toString('hex'))
        });
    })
}

async function verify(password, hash) {
    return new Promise((resolve, reject) => {
        const [salt, key] = hash.split(":")
        crypto.scrypt(password, salt, 64, (err, derivedKey) => {
            if (err) reject(err);
            resolve(key == derivedKey.toString('hex'))
        });
    })
}

(async function run () {
    const password1 = await hash("123456")
    const password2 = await hash("123456")
    console.log("password1", await verify("123456", password1));
    console.log("password2", await verify("123456", password2));
    console.log("password1 == password2", password1 == password2);   
})()
  • 2
    Does this answer your question? [NodeJS: bcrypt vs native crypto](https://stackoverflow.com/questions/6951867/nodejs-bcrypt-vs-native-crypto) – Adam Azad Nov 29 '20 at 09:41
  • Either one should be fine. Much more important is using an appropriately large iteration count and a unpredictable salt for every password. I think scrypt may have some advantages but bcrypt is more commonly supported. – President James K. Polk Nov 29 '20 at 20:21
  • I'd advise `bcrypt` over NodeJS's built in `crypto` (read: `crypto.scrypt`). The reason for is that bcrypt is more of a plug-n-play solution, that has most of the security included by default. E.g. bcrypt can generate salt for you. bcrypt is not [vulnerable to timing attacks,](https://github.com/bcrypt-ruby/bcrypt-ruby/pull/43) which you would have to handle yourself with `crypto.timingSafeEqual` - making your code example `password1 == password2`vulnerable ([here is an example how](https://stackoverflow.com/a/67038052/3673659)). Unless you know some things about password hashing, use bcrypt. – Advena Jan 24 '23 at 07:23

0 Answers0