Nodejs provides crypto modules to perform the encryption and hashing of sensitive information such as passwords. The Bcrypt node modules provides easy way to create and compare hashes.
Let’s learn how to use it.
Installation and usage
To use the library, simply install with NPM:
Then include it in your project.
Creating and Verifying Hash
Bcrypt provides both synchronous and asynchronous methods. I recommend asynchronous method because hashing is CPU intensive, and the synchronous version will block the event loop and prevent your app from handling other requests until it finishes.
Here is the code for hashing using asynchronous method. First argument is the password and second argument is number of rounds for the salt generation.
To verify the hashed password you can use the following code:
That’s it. Easy as cake.
You must always hash your password or any sensitive information that you don’t need in original form again. Hashing is one way that means you can’t get the original data back from the hash but regenerate same hash using the original data.