Step 5: Hash password

Let's fix a considerable security risk in our application!

You should never store users' passwords in a database! Instead, you must encode the password and keep the encoded version.

To mitigate the issue, we will hash the user password and save the hashed password!

  • A hashed password has been run through a function that generates a long encrypted string from the original password.
  • The same password run through the same hash function will generate the same response. This process is how we can match passwords when users log in.

Install the bcryptjs package:

yarn add bcryptjs

Bcrypt is a common library for password hashing in web apps!

Create a new file src/password.js

import bcrypt from "bcryptjs";

export const hashPassword = (password) => {
  try {
    const salt = bcrypt.genSaltSync(10);
    const hashedPassword = bcrypt.hashSync(password, salt);
    return hashedPassword;
  } catch (err) {
    throw err;
  }
};

export const verifyPassword = (plainPassword, hashedPassword) => {
  return bcrypt.compareSync(plainPassword, hashedPassword);
};

The input to genSaltSync is the value for "salt round," which is the cost factor in the BCrypt algorithm. The cost factor controls how much time is needed to calculate a single BCrypt hash. The higher the cost factor, the more hashing rounds are done. Increasing the cost factor by one doubles the necessary time needed for password cracking thorugh brute-forcing.