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.
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('mypassword', 10);
console.log(hash);$2b$10$N9qo8uLOickgx2ZMRZoMy...hash() salts and hashes the password using 10 salt rounds.
const match = await bcrypt.compare('mypassword', hash);
console.log(match);truecompare() 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.
