Hashing passwords in NodeJS with bcrypt library

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.

 We can install this package by using this command.

npm install bcryptjs
// Requiring module
const bcrypt = require('bcryptjs');

const password = 'pass123';
const 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);
				}
			})
	})
})
Output: 

$2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm
Encrypted password is: pass123 
Decrypted password is: $2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm

Leave a comment

Your email address will not be published. Required fields are marked *