Password Verification in Node.js
Last Updated :
14 Oct, 2021
In Node for password hashing and verification we can use a npm library known as bcryptjs npm-bcryptjs.
Installation of bcryptjs: Node.js contains an inbuilt crypto module’s randomBytes interface which is used to obtain the secure random numbers.
npm install bcryptjs
Approach:
- To hash a password use bcrypt.hash(plainTextPassword, salt, callback) which returns a promise if no callback is passed.
- To verify plain text password with hashed password use bcrypt.compare(plainTextPassword, hashedPassword, callback) which also returns a promise if no callback is passed.
Example 1:
const bcrypt = require( "bcryptjs" );
const password = "password123" ;
bcrypt.hash(password, 8, (err, hashedPassword) => {
if (err) {
return err;
}
console.log(hashedPassword);
bcrypt.compare(password, hashedPassword, (err, isMatch) => {
if ( err ) {
return err;
}
console.log(isMatch);
});
});
|
Output:
$2a$08$PV4rYpBwXUPAGuMedxUnAOxq/TozK9o/QSUWaKE1XL8psOyZ.JL4q
true
Example 2:
const bcrypt = require( "bcryptjs" );
const password = "password123" ;
bcrypt.hash(password, 8).then(hashedPassword => {
console.log(hashedPassword);
return bcrypt.compare(password, hashedPassword);
}).then(isMatch => {
console.log(isMatch);
}). catch (err => {
console.log(err);
});
|
Output:
$2a$08$LKZU9S9WVs3C.S/zpu2U7eua/ocfzD1ytF68QPT5M600auT6M.SxG
true
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...