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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


Output:

$2a$08$PV4rYpBwXUPAGuMedxUnAOxq/TozK9o/QSUWaKE1XL8psOyZ.JL4q
true

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


Output:

$2a$08$LKZU9S9WVs3C.S/zpu2U7eua/ocfzD1ytF68QPT5M600auT6M.SxG
true


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.