🎓 A1Learner
🔍
0 of 50 lessons completed

Password Hashing

Password hashing turns a password into a fixed scrambled string. The scrambled string is stored, and the plain password is never stored.

Making a hash

hashSync mixes in a salt.

const hash = bcrypt.hashSync('green-apple-42', 10);

Checking a password

compareSync answers true when the password matches.

const hash = bcrypt.hashSync('green-apple-42', 10);
console.log(bcrypt.compareSync('green-apple-42', hash));

Example

import bcrypt from 'bcryptjs';

const password = 'green-apple-42';
const hash = bcrypt.hashSync(password, 10);
console.log(bcrypt.compareSync(password, hash));
console.log(bcrypt.compareSync('wrong-password', hash));

Key points

  • A hash is a one-way scramble of the password.
  • The same password makes a different hash each time.
  • A salt is a random value mixed into each hash.
  • bcrypt is a small library that makes and checks hashes.
  • Login checks the typed password against the stored hash.

In this example, the script hashes one password first. It then checks the right password against the hash. It also checks a wrong password against the same hash. The hash itself is never printed.

Note

A hash cannot be turned back into the password.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is stored in the database for a user password?