Password Verification in Node
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); }); }); |
chevron_right
filter_none
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); }); |
chevron_right
filter_none
Output:
$2a$08$LKZU9S9WVs3C.S/zpu2U7eua/ocfzD1ytF68QPT5M600auT6M.SxG true
Recommended Posts:
- Node | URL.password API
- Automatic Captcha Verification using JavaScript
- jQuery | :password Selector
- Password Matching using JavaScript
- HTML | <input type="password">
- HTML | DOM Anchor password Property
- Validate a password using HTML and JavaScript
- Show and hide password using JavaScript
- HTML | DOM Input Password Object
- HTML | DOM Input Password name Property
- HTML | DOM Input Password value Property
- MySQL | Change User Password
- Node.js | NPM (Node Package Manager)
- JavaScript | Program to generate one-time password (OTP)
- HTML | DOM Input Password autocomplete Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


