Password Verification in Node.js
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:
// Use bcryptjs module const bcrypt = require( "bcryptjs" ); // Store the password into variable const password = "password123" ; // Use bcrypt.hash() function to hash the password bcrypt.hash(password, 8, (err, hashedPassword) => { if (err) { return err; } // Display the hashed password console.log(hashedPassword); // Use bcrypt.compare() function to compare // the password with hashed password bcrypt.compare(password, hashedPassword, (err, isMatch) => { if ( err ) { return err; } // If password matches then display true console.log(isMatch); }); }); |
Output:
$2a$08$PV4rYpBwXUPAGuMedxUnAOxq/TozK9o/QSUWaKE1XL8psOyZ.JL4q true
Example 2:
// Use bcryptjs module const bcrypt = require( "bcryptjs" ); // Store the password into variable const password = "password123" ; // Use bcrypt.hash() function to hash the password bcrypt.hash(password, 8).then(hashedPassword => { // Display the hashed password console.log(hashedPassword); // Compare the password with hashed password // and return its value return bcrypt.compare(password, hashedPassword); }).then(isMatch => { // If password matches then display true console.log(isMatch); }). catch (err => { // Display error log console.log(err); }); |
Output:
$2a$08$LKZU9S9WVs3C.S/zpu2U7eua/ocfzD1ytF68QPT5M600auT6M.SxG true