/

How to Use the JavaScript bcrypt Library

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
2
3
4
5
6
7
8
9
10
11
12
import bcrypt from 'bcrypt';

const password = 'oe3im3io2r3o2';
const rounds = 10;

bcrypt.hash(password, rounds, (err, hash) => {
if (err) {
console.error(err);
return;
}
console.log(hash);
});

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
2
3
4
5
6
7
bcrypt.compare(password, hash, (err, res) => {
if (err) {
console.error(err);
return;
}
console.log(res); // true or false
});

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
2
3
4
5
6
7
const hashPassword = async () => {
const hash = await bcrypt.hash(password, rounds);
console.log(hash);
console.log(await bcrypt.compare(password, hash));
};

hashPassword();

Feel free to check out a couple of example usages of bcrypt in this Glitch project.

Tags: bcrypt, JavaScript, password hashing, security, npm package