Node.js ยท Chapter 28 of 43

Hashing Passwords

Passwords must never be stored in plain text. Hashing transforms a password into a fixed-length, irreversible string, so even if a database leaks, raw passwords stay protected.

The `bcrypt` library is a widely used, purpose-built tool for securely hashing and comparing passwords.

Hashing a password

`bcrypt.hash()` generates a salted hash from a plaintext password; the salt makes each hash unique even for identical passwords.

Verifying a password

`bcrypt.compare()` checks a plaintext password against a stored hash without ever reversing the hash.

Example 1 (javascript)
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('mypassword', 10);
console.log(hash);
Output
$2b$10$N9qo8uLOickgx2ZMRZoMy...

hash() salts and hashes the password using 10 salt rounds.

Example 2 (javascript)
const match = await bcrypt.compare('mypassword', hash);
console.log(match);
Output
true

compare() returns true if the plaintext matches the stored hash.

Key points

  • Never store plaintext passwords.
  • bcrypt.hash() creates a salted, irreversible hash.
  • bcrypt.compare() safely verifies a password against a hash.
  • Higher salt rounds increase security but also increase computation time.
๐Ÿ’ก Note: Hashing is one-way; there is no way to 'unhash' a password, only to compare against it.

๐Ÿ“ Quick Quiz

1. Why hash passwords instead of storing them directly?

2. Which bcrypt method checks a password against a hash?

3. What does a 'salt' do in password hashing?