Password encryption in Node.js using bcryptjs module
Last Updated :
31 Mar, 2023
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 to anyone, Node.js uses “bcryptjs”.
This module enables storing 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
Example:
Javascript
const bcrypt = require( 'bcryptjs' );
const password = 'pass123' ;
const hashedPassword;
bcrypt.genSalt(10, function (err, Salt) {
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) {
if (isMatch) {
console.log( 'Encrypted password is: ' , password);
console.log( 'Decrypted password is: ' , hashedPassword);
}
if (!isMatch) {
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...