GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Check if a File Exists in Node.js
  • Working with UUID in Node
  • Working with the Node.js assert Library
  • Modify Authorized redirect_uris For Google OAuth
  • Sleep in NodeJS
  • Fundamentals
  • Node
  • Vue
  • Webpack
  • Axios
  • Mongoose
  • Express
  • Lodash
  • npm

This view

  • Original page
  • New address

GeezerVison is showing masteringjs.io — Using bcrypt-js to Hash Passwords in JavaScript

Mastering JS Logo
Mastering JS
Tutorials Newsletter eBooks Jobs
☰
Tutorials Newsletter eBooks Jobs
Tutorials / Node /

Using bcrypt-js to Hash Passwords in JavaScript

Sep 30, 2022

bcrypt's hash() function is how to create a secure hash of a password. It takes two parameters: the password and the number of salt rounds. Increasing the number of salt rounds makes bcrypt.hash() slower, which makes your passwords harder to brute force.

const bcryptjs = require('bcryptjs');

const numSaltRounds = 8;

const password = 'password';

bcryptjs.hash(password, numSaltRounds);

We generally recommend a higher numSaltRounds in production (at least 8). However, we often use numSaltRounds = 1 in tests to make tests run faster.

The bcrypt-js library also has a bcryptjs.hashSync(password, numSaltRounds) function. We recomment not using hashSync(), because hashSync() will block your entire Node process while it runs.

compare()

The compare() function is used to essentially decrypt the password. It takes two parameters: the password and the hash. If the function returns true, then the password passed was the correct password.

const bcryptjs = require('bcryptjs');

const numSaltRounds = process.env.NODE_ENV === 'test' ? 1 : 12;

const password = 'password';

const hash = bcryptjs.hash(password, numSaltRounds);

bcryptjs.compare(password, hash); // true

There is no way to get the original password from the bcrypt hash without guessing the password.

Make sure you use the exact same number of salt rounds when generating the hash using hash(), and when comparing using compare(). If you compare() using a different number of salt rounds than the hash was generated with, compare() will always fail.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Node Tutorials

  • Getting Started with Oso Authorization in Node.js
  • Check if a File Exists in Node.js
  • How To Fix "__dirname is not defined" Error in Node.js
  • Working with UUID in Node
  • Working with the Node.js assert Library
  • Modify Authorized redirect_uris For Google OAuth
  • Sleep in NodeJS
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.