Hash Passwords in Node.js
What is bcrypt?
Bcrypt is a password hashing algorithm designed by Niels Provos and David Mazières based on the Blowfish cipher. The name “bcrypt” comprises two parts: “b” representing Blowfish and “crypt,” which denotes the hashing function utilized by the Unix password system. This blog will show you how to use bcrypt password hashing with the bcrypt library in Node.js and avoid data breaches.
Prerequisite:
Node.js and npm: Ensure they are installed on your machine. Visit https://nodejs.org/ to download and follow the installation instructions.
bcrypt’s hash()
function is how you create a secure hash of a password. It takes two parameters: the password and the number of salt rounds. Increasing the number of salt rounds makes bcrypt.hash()
slower, which makes your passwords harder to brute force.
const bcryptjs = require('bcryptjs'); const numSaltRounds = 8; const password = 'helloworld@123'; bcryptjs.hash(password, numSaltRounds);
In the test environment, we recommend using a salt value of 1, while for production, we recommend using a salt value greater than 8.
The compare()
function is used to essentially decrypt the password. It takes two parameters: the password and the hash. If the function returns true, then the password passed was the correct password.
const bcryptjs = require('bcryptjs'); const numSaltRounds = 8; const password = 'helloworld@123'; const hash = bcryptjs.hash(password, numSaltRounds); bcryptjs.compare(password, hash); // true
Note: Make sure you use the same number of salt rounds when generating the hash using hash(), and comparing using compare() function. There is no way to get the original password from the bcrypt hash.
Conclusion
This is how simple it is password hashing in Node.js. It is crucial to secure data to avoid significant damage. An attacker may find a way to access your data storage, but well-encrypted passwords are a waste of time and effort for an attacker. They won’t get any benefits from our encrypted data. Node.js allows us to use bcrypt without any hurdles. There is no reason to avoid it when dealing with users’ passwords and other sensitive data. A secure hashing function such as bcrypt should be necessary to make a robust system. I suggest you use it to store passwords. You won’t have to deal with problems exposing users’ sensitive information if you have done hashing using bcrypt.