Section 31 – Lesson 404 – Complete 2020 Web Development Bootcamp

Lesson 404 – Salting & Hashing Passwords with bcrypt

In order to prevent dictionary attacks and hash table attacks we have to use “salting”.

“Salting” adds another layer of protection by generating a random set of characters which are then combined with the user input password and then put through the hash function. The resulting hash is created from both the password as well as the random “salt”.

The “salt” is stored in the database along with the hash.

Using the npm md5 package is still not that secure even when using a “salt”. A more secure encryption package is bcrypt which uses “salt rounds”.

One “salt round” using bcrypt is to take the user password then add a salt and pass the password and the salt through the hash function.

A second “salt round” would take the hash generated by the first round then add the same salt used in the first round and run the hash and the salt through the hash function to generate another hash.

Bcrypt allows you to set the number of rounds you want to salt your password.

The first step in implementing bcrypt is to install it in the project directory using this code in the terminal –

npm i bcrypt@3.0.6

This will install the stable version of bcrypt (at the date of this post).

The next step is to require bcrypt in the app.js file –

const bcrypt = require("bcrypt");

You then define the number of salt rounds in the app.js file –

const saltRounds = 10;

The next step is to refactor the app.post(“/register”) and the app.post(“/login”) routes to use bcrypt. The refactored code is –

app.post("/register", function(req, res) {

	bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
		const newUser = new User({
		email: req.body.username,
		password: hash

		});

	newUser.save(function(err) {
		if (err) {
			console.log(err);
		} else {
			res.render("secrets");
		}
		});
	});

});

app.post("/login", function(req, res) {
	const username = req.body.username;
	const password = req.body.password;

	User.findOne({email: username}, function(err, foundUser) {
		if (err) {
			console.log(err);
		} else {
			if (foundUser) {
			  bcrypt.compare(password, foundUser.password, function(err, result) {
	if (result === true) {
		res.render("secrets");
	}
	});
						
	}
    }
  });
});