How to Use the JavaScript bcrypt Library
Learn how to securely hash and check passwords in JavaScript using the bcrypt library.
The bcrypt npm package is widely used for working with passwords in JavaScript, providing a secure way to store and compare hashed passwords.
As a basic rule of security, passwords should never be stored in plain text format in databases or any other storage. Instead, a hash of the password should be generated and stored.
Here is an example of generating a hash using bcrypt:
1 | import bcrypt from 'bcrypt'; |
The bcrypt.hash()
function takes the password as the first argument and the number of rounds for the hash as the second argument. The higher the number of rounds, the more secure the hash, but it also takes longer to generate.
According to the bcrypt library README, on a 2GHz core, the following number of hashes can be generated per second:
- rounds=8: ~40 hashes/sec
- rounds=9: ~20 hashes/sec
- rounds=10: ~10 hashes/sec
- rounds=11: ~5 hashes/sec
- rounds=12: 2-3 hashes/sec
- rounds=13: ~1 sec/hash
- rounds=14: ~1.5 sec/hash
- rounds=15: ~3 sec/hash
- rounds=25: ~1 hour/hash
- rounds=31: 2-3 days/hash
It’s important to note that each time you call bcrypt.hash()
, the resulting hash will be different. This feature is crucial as it prevents the original password from being reconstructed from the hash.
To check if a password matches a given hash, you can use the bcrypt.compare()
function:
1 | bcrypt.compare(password, hash, (err, res) => { |
If the resulting res
value is true
, it means the password matches the hash, and you can proceed with actions such as allowing a user to log in successfully.
Alternatively, you can use the promise-based API of the bcrypt library:
1 | const hashPassword = async () => { |
Feel free to check out a couple of example usages of bcrypt in this Glitch project.
Tags: bcrypt, JavaScript, password hashing, security, npm package