How to encrypt and decrypt Passwords with Bcrypt Nodejs?

How to encrypt and decrypt Passwords with Bcrypt Nodejs?

80% of hacking-related breaches are linked to passwords, according to a study carried out by Version on 868 cases. One of the reasons for these breaches is that developers refuse to use to encrypt and decrypt passwords with bcrypt-nodejs and other secure encryption tools.

User data encryption is a major block when creating authentication and authorization systems for your web apps. One very trusted and trusted encryption module in nodeJs is Bcrypt. With Bcrypt, you can hash and verify users’ data and passwords with no stress.

Are you ready to use bcrypt for your next web application project?

Don’t worry. You will learn how to encrypt and decrypt user passwords and data with bcrypt-nodejs.

Let’s go!

What Is Bcrypt?

Bcrypt is an NPM library that helps secure users’ credentials in NodeJs.

It supports both synchronous and asynchronous methods.  However, an asynchronous method will not stop other processes from running.

The Bcrypt hashing algorithm was designed on the Blowfish cipher. The name bcrypt was coined from ‘b’ and ‘crypt’. The ‘b’ stands for ‘blowfish’, and the crypt is the hashing function used by a Unix. 

Niels Provos and David Mazieres created Bcrypt. The duo noticed that due to hardware and technology advancements. The crypt was no longer secure to encrypt users’ data. Then they designed the bcrypt, which is a slower algorithm to hash. Since it is a password hashing algorithm, having a slow hashing speed makes it less prone to brute-force attacks.

How to Install Bcrypt-Nodejs?

To install the bcrypt using npm in Node.js. You can use the following command.

 npm install bcrypt - - save

Using yarn

 yarn add bcrypt

However, to successfully install the bcrypt library, you need to meet some dependencies requirements. Here is the list of bcrypt dependencies you must meet before using bcrypt.

  • NodeJS
  • Node-gyp – Please check the dependencies for this tool at: https://github.com/nodejs/node-gyp
  • Windows users will need the options for C# and C++ installed with their visual studio instance.
  • Python 2.x/3.x
  • OpenSSL – This is only required to build the bcrypt project if you use version <= 0.7.7. Otherwise, we’re using the built-in node crypto bindings for seed data (which use the same OpenSSL code paths we were but don’t have the external dependency).

How To Use Bcrypt In Nodejs

To use bcrypt in Nodejs, you have to import the library and define your salt round as a cost or work factor. After that, you need to generate the salt and hash the password. The hashed password can then be stored in your database.

When it’s time for your user to authenticate, you can compare and verify the hashed password with bcrypt. If the values return true, the user can access their resources. 

Now, let’s take all these processes one after the other and implement them with code examples.

To get started with bcrypt in your project. You can use this code:

const bcrypt = require('bcrypt');

const saltRounds = 10;

const myPassword = ‘kjanfv348030qa';

After you have imported the bcrypt library, and declared the required variables as shown in the above example. The next step is to hash the password.

How To Hash Password With Bcrypt In Nodejs

To hash your password with bcrypt, you must generate a salt using the `genSalt` method. There are two ways to generate salt using bcrypt. You can either auto-generate salt or generate the salt and hash separately. 

After you generate the salt, you can go on to hash the password with the `hash method. 

Also, it is worth knowing that you can hash passwords using the asynchronous and synchronous approaches. However, async methods are common because hashing done by bcrypt is CPU intensive. Therefore, the sync methods will block any event loop, and your application will not serve any other request until the sync method completes its operation.

How To Encrypt and Hash Passwords In Node.Js Using Async Promise

This method allows you to generate a salt and hash using separate functions. For this example, we will use the javascript promise returned by the async function. When the Promise is returned, we can handle the operations on success or failure.

bcrypt.genSalt(saltRounds)
.then(salt => {
   console.log(‘This is the salt:’, salt);
  return( bcrypt.hash(myPassword, salt))
})
.then( hash => {
   console.log(hash)
  //Do whatever you want with the hash
})
.catch(err => {
console.error(err.message)
})

In the above example, we generated a salt by using the genSalt method. The method takes in the saltRounds we declared as an argument. On success, the method returns a salt that we used as an argument for the “.hash” method. The bcrypt.hash returns a hashed password when the operation is successful.

The hashed password is stored in the database along with other details.

Suppose there is any error during the cause of the process. The .catch returns the error and logs it to our console.

You will get a different hash value from special salt every time you re-run this code. This is how the bcrypt prevents a rainbow table attack.

How to Auto-generating a salt and hash in Bcrypt

Now, let’s look at the second method of bcrypt on how to auto-generate the salt and hash in one function:

bcrypt.hash(myPassword, saltRounds)
.then(hash => {
  console.log('Hash ', hash)
  })
.catch(err => console.error(err.message))

Here, we only called the hash function. The hash function takes the plain myPassword and the saltRound. Then it generates the salt before generating the hash automatically. Also, this method generates a unique hash each time.

How To Verify A Password With Bcrypt in NodeJs

Now, it’s time to verify a user’s password with bcrypt. This operation will be useful for performing user logins. To do that, we must compare the given password with the stored password in our database. The bcrypt.compare method take care of that part for us.\

bcrypt.hash(myPassword, saltRounds)
.then(hash => {
     console.log('Hash ', hash)
     validatePassword(hash)
  })
 .catch(err => console.error(err.message))

function validatePassword(hash) 
  bcrypt.compare(password, hash)
  .then(isValid => {
        console.log(isValid) // return true
      })
      .catch(err => console.error(err.message))        
}

If isValid is true, the password-generated hash for it is matched.

Conclusion

Now that you’ve learned how to encrypt and decrypt passwords in NodeJs. You can apply these methods in your projects. Protecting users’ data is your priority as a developer, and you must take that job seriously.

When next, you are building an API or an authentication system in NodeJs. Don’t forget to use a good hashing algorithm like bcrypt.

Are you interested in learning how to build a user signup, login, and authentication system in NodeJs?

Check out our article on NodeJ login and Authorization.