Languages
[Edit]
EN

Node.js - hash passwords using bcrypt

0 points
Created by:
Selina-Miranda
737

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

Hashing password using Bcrypt
Hashing password using Bcrypt

Storing user passwords in a database requires security in case they are disclosed
or someone unauthorized had access to our database. 

Note:
Passwords in our database should never be stored explicitly - they should always be hashed.

Currently, the most popular and safe method is to use bcrypt.

First step is to install bcrypt using npm:

npm install bcrypt

Hash a password

Note: 
The hashing method requires salt rounds, i.e. the cost factor - simply speaking, it is a cost function (the larger, the more encrypted the password) - the recommended value is 10.

const bcrypt = require('bcrypt');

const saltRounds = 10; 
const password = '1234567';

bcrypt.hash(password, saltRounds, (error, hash) => {
    if (error) {
        console.log('Error: ', error);
    } else {
        console.log(`Your encrypted password is: ${hash}`)
        // here you can send hashed passwords to the database
    }
});

Check a password

Compare the given password with the password from the database.

const bcrypt = require('bcrypt');

const password = '1234567';
const hashedPassword ='P@$$WoRD';

bcrypt.compare(password, hashedPassword, (error, result) => {
    if (error) {
        console.error('Error: ', error);
    } else {
        console.log('Is the password correct: ', result); // true or false
    }
});

Note: bcrypt uses an algorithm that creates different hashed passwords each time, but comparing the passwords for each password will give true. Check out this question.

Resources

  1. Bcrypt - Wikipedia.
  2. Node.js - why bcrypt generate different outputs for same input (question).

Alternative titles

  1. Node.js - hashing passwords using bcrypt
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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