Hashing Passwords in Node js
What is a Password Hashing
For every web developer, one of the most important jobs is the user data to be safe and secure from the outside world. Important user data like passwords should not be kept raw in the database, and the best way to protect the passwords is to use salted password hashing.
To hash a password we must be using hash algorithms, that are one-way functions. They convert any amount of data into a fixed-length "fingerprint" that is not possible to be reversed. This is great for securing passwords because we can store the password in a form that is not usable if stolen, but we also need to be able to verify that the password is correct.
How to Hash a Password in Node.js
For us to be able to use password hashing in Node.js, firstly we need to install a NPM package called bcrypt, with the npm i bcrypt
command. After the package is installed we need to setup the hashing and salting structure.
Structure example:
const bcrypt = require('bcrypt'); //Importing the NPM bcrypt package.
const saltRounds = 10; //We are setting salt rounds, higher is safer.
const myPlaintextPassword = 's0/\/\P4$$w0rD'; //Unprotected password
/* Here we are getting the hashed password from the callback,
we can save that hash in the database */
bcrypt.hash(myPlaintextPassword, saltRounds, (err, hash) => {
//save the hash in the db
});
/* Here we can compare the hashed password after we get it from
the database with the plaintext password */
bcrypt.compare(myPlaintextPassword, hash, function(error, response) {
// response == true if they match
// response == false if password is wrong
});
The first function hash()
is for hashing the plain text password, we have myPlaintextPassword as our first parameter which is our password as the user input it, second param is the salt rounds which is the number of rounds we are doing to secure the password(higher is better but can take a lot of time, 10 is recommended as default). In the callback, we can get an error if there is some error or hash which is our hashed password, ready to be stored in the database.
The second function compare()
is used to check the user entered password with the hashed password (like when the user is trying to log in). We have myPlaintextPassword as the first parameter which is like before the password from the user, and the second parameter is the hashed password which we should get it from the database before. If myPlaintextPassword(it is hashed too) matches the hashed password from our database the response we get will be equal to true, else the response will be false, and then we can inform the user if the password is correct or not.
Password hashing is a very important security technique when storing passwords in the database, as developers we must protect and keep the data secured.
Tweet