How to hash passwords with bcrypt
In this article, we will show how we can use bcrypt in our NodeJs API to securely hash passwords and compare them.
Bcrypt is a popular hashing algorithm that are considered secure, however, as with all password management, we should always do our best to make it as hard as possible to hack the passwords so it is essential that e.g salting is used. In this guide, we will cover both how we can hash a password and to apply salting to it.
Download
There is a npm module that can be downloaded and used in our NodeJs application
npm i bcrypt
Hash the password
Let's write a password generator function that will use bcrypt to hash it, we will apply salting as well in this example
const bcrypt = require("bcrypt"); const saltRounds = 10; async generatePassword(password) { const hashed = await bcrypt.hash(password, saltRounds); return hashed; }
In above example, we will hash the password and apply 10 salt rounds to it.
await generatePassword("admin123"); // $2b$10$/B5I3.bLJOJvjgiyZ7kKLenTcJ/5tk8Oc8yUqeJmpH0N48evetMwy
There we go. Since the hashed value will change everytime we call it, we will use the built in compare() function in bcrypt to do our comparison.
Compare the password
Let's write another function that will compare our password with the hashed value
async isValid(hashed, password) { return await bcrypt.compare(password, hashed); }
And now we will try it with our password and hashed value
await isValid( "$2b$10$/B5I3.bLJOJvjgiyZ7kKLenTcJ/5tk8Oc8yUqeJmpH0N48evetMwy", "admin123" ); // true
There we go!
Outro
In this article we briefly showed how to use bcrypt in a NodeJs application and how we can hash password with salting and how we later can compare the hash and the password. I hope you enjoyed this article, and that it helped you move forward with your password management.
All the best,