Languages
[Edit]
EN

Node.js - hash password using bcrypt

0 points
Created by:
Sujay
272

In this article, we would like to show you how to hash password using bcrypt in Node.js.

Introduction

Before we start, there are some terms you need to know:

  • salt - random string added to the text to be hashed. The algorithm uses the salt to hash the text so the output isn't predictable,
  • salt round - the cost factor that indicates the amount of time needed to calculate a single bcrypt hash. The higher the saltRounds value, the more hashing rounds are done. Increasing the cost factor by 1 doubles the time.

Hashing password with bcrypt

1. Install bcrypt

npm install --save bcrypt

2. Import bcrypt in your project

const bcrypt = require('bcrypt');

3. There are two ways to hash the password:

  1. generate a salt and hash on separate function calls
  2. auto-generate a salt and hash

3.1 Generate a salt hash on separate function call.

Specify the number of salt rounds, generate the salt using bcrypt.genSalt() and finally hash the password.

Practical example:

const bcrypt = require('bcrypt');

const saltRounds = 10;
const password = 'ExamplePassword';

bcrypt.genSalt(saltRounds, (err, salt) => {
    bcrypt.hash(password, salt, (err, hash) => {
        // Now you can store the hashed password db
    });
});

3.2 Auto-generate a salt and hash

const bcrypt = require('bcrypt');

const saltRounds = 10;
const password = 'ExamplePassword';

bcrypt.hash(password, saltRounds, (err, hash) => {
    // Now you can store the hashed password db
});

Note:

Both 3.1 and 3.2 techniques achieve the same result.

Example result:

$2b$10$0RnTuEvZVkygwVi49AYWCuaPPJubSsoOtEaVrw2vgac4tmS6aIHxS

4*. Compare the password entered by the user with the previously stored password hash

// Load hash from your password db.
bcrypt.compare(plainPassword, hash, function (err, result) {
    // if result === true, password matched
    // if result === false, wrong password
});

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join