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);   
})()

3
  • 2
    Does this answer your question? NodeJS: bcrypt vs native crypto
    – Adam Azad
    Nov 29, 2020 at 9: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. Nov 29, 2020 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, which you would have to handle yourself with crypto.timingSafeEqual - making your code example password1 == password2vulnerable (here is an example how). Unless you know some things about password hashing, use bcrypt.
    – Tanckom
    Jan 24 at 7:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy