Hash password node js

Hashing passwords using Bcrypt with Nodejs

According to Wikipedia “bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher.

In real life applications with User authentication functionality, it is not practical to store user password as the original string in the database but it is good practice to hash the password and then store them into the database.

Bcrypt package for Node JS helps developers to hash user password.

Install via NPM

npm install bcrypt

Cryptography terms

Before we use it, let’s first have a look at some terms.

Salt Rounds: This is the cost factor that indicates the amount of time needed to calculate a single bcrypt hash. Higher the salt rounds, the more hashing rounds are done, hence the time and difficulty is increased while brute-forcing. For example, a cost factor of n means that the calculation will be done 2^n times.

Implementation

const bcrypt = require('bcrypt');
const saltRounds = 10;
const yourPassword = "someRandomPasswordHere";

Technique 1 (generate a salt and hash on separate function calls):

bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
        // Store hash in your password DB.
    });
});

Technique 2 (auto-gen a salt and hash):

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
    // Store hash in your password DB.
});

Note that both techniques achieve the same end-result.

To check a password:

// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
    // result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
    // result == false
});
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

two × 2 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top