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);
})()
bcrypt
over NodeJS's built incrypto
(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 withcrypto.timingSafeEqual
- making your code examplepassword1 == password2
vulnerable (here is an example how). Unless you know some things about password hashing, use bcrypt.