Security is one of the most important thing for any organization. Saving the password in the Backend is very tricky for beginner developers some of them even store the password in plain text. In this article we will gonna learn how to store encrypted password in backend.
Problem with storing plain password
Let’s assume we have store password hello in the backend in plain text and after some time our backend is hacked in that case our all users data will be compromised. The hacker will get access to millions of user data. To handle this case we prefer to store the password in encrypted form.
It is a password hashing function use to convert plain text password into encrypted form using some algorithms. Bcrypt is one of the standard way to store the password in database. The benefit of bcrypt is that even if the db is compromised hacker can’t use the user’s password to gain access.
Like any other package we can simply install bcrypt from npm.
npm install bcrypt --save
To convert password into encrypted form
const bcrypt = require('bcrypt'); const password = "hello"; const encPass = await bcrypt.hash(password, 10);
we simply need to use bcrypt.hash function to get encrypted password. This function accepts only two argument i.e password and no of rounds to convert into hash.
Check for valid password
While login we don’t need to convert password again instead of that we just need to compare both passwords (plain password and stored password in db).
const result = await bcrypt.compare(password, storedPass);
bcrypt.compare accepts only two arguments first is the plain text and second is the stored encrypted password from db. It will gonna return boolean value.