Getting Started With Node – Course

Using Bcrypt Module

The bcrypt node modules provide an easy way to create and compare hashes. Let’s learn how to use it.

First, install the module.

npm i --S bcrypt

Generate a hash

Here is the code to generate a hash.

const bcrypt = require('bcrypt');

bcrypt.hash('data', 10, (err, hash) => {
   if(err) {
      console.log('error...');
      return;
   }
   console.log(hash);
});

Here is how to verify the hash.

const bcrypt = require('bcrypt');

bcrypt.compare('data', hash, (err, result) => {
   if(err) {
      console.log('error...');
      return;
   }
   if(result) {
     // hash matched
   } else {
    // hash does not match
   }
});

You can use this module to generate a hash for passwords and store them in the database. You can later compare it with the password entered by the user.

For more information about password hashing, read this article.

Leave a Reply

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

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