Password encryption in Node.js using bcryptjs module
While submitting a form, there are some sensitive data (like passwords) that must not be visible to anyone, not even to the database admin. To avoid the sensitive data being visible from anyone, Node.js uses “bcryptjs”.
This module enables storing of passwords as hashed passwords instead of plaintext.
Installation of bcryptjs module:
- You can visit the link to Install bcryptjs module. You can install this package by using this command.
npm install bcryptjs
- After installing bcryptjs module you can check your request version in the command prompt using the command.
npm version bcryptjs
- After that, you can create a folder and add a file for example index.js, To run this file you need to run the following command.
node index.js
index.js
// Requiring module const bcrypt = require( 'bcryptjs' ); const password = 'pass123' ; var hashedPassword; // Encryption of the string password bcrypt.genSalt(10, function (err, Salt) { // The bcrypt is used for encrypting password. bcrypt.hash(password, Salt, function (err, hash) { if (err) { return console.log( 'Cannot encrypt' ); } hashedPassword = hash; console.log(hash); bcrypt.compare(password, hashedPassword, async function (err, isMatch) { // Comparing the original password to // encrypted password if (isMatch) { console.log( 'Encrypted password is: ' , password); console.log( 'Decrypted password is: ' , hashedPassword); } if (!isMatch) { // If password doesn't match the following // message will be sent console.log(hashedPassword + ' is not encryption of ' + password); } }) }) }) |
Step to run the application: Run the application using the following command:
node index.js
Output: We will see the following output on the console screen.
$2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm
Encrypted password is: pass123
Decrypted password is: $2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm