How to create a strong and secure password in Node.js that cannot be decrypted
The best way to create a strong password
To create a strong password, We will use a very popular npm library known as bcryptjs
which allows us to encrypt the plain text password.
The algorithm used in this library is a hashing algorithm.
The difference between encrypting a password and hashing a password is that encrypted passwords can be decrypted if we know the decryption key, but the hashing algorithm does not allow decryption and is more secure.
So let’s dive into it
Installation:
To install the package execute the following command from the terminal
npm install bcryptjs
To hash the password, it provides a hash method which returns a promise with the generated hashed password
const bcrypt = require("bcryptjs");
bcrypt.hash("thisismypassword", 8)
.then(password => {
console.log(password); // hashed password
});
The hash function accepts two arguments
1. Plain text password
2. The number of times the hashing algorithm should be executed to get a strong password and the recommended value by the author is 8 which will create a strong password and also will not take much time to hash it.
Now, you might be thinking about, how we can check if the password entered by the user is the same as the hashed password you might have stored in the database if it cannot be decrypted.
For that, bcryptjs
provides a compare method that allows us to compare the plain text password and hashed password stored in the database.
The compare
methods accept the following arguments
1. The plain text password
2. The hashed password to compare against
and it returns a promise with a boolean result.
If the passwords are matched, the result is true otherwise false.
bcrypt.hash("thisismypassword", 8)
.then(password => {
bcrypt.compare("thisismypassword", password)
.then(isEqual => {
console.log(isEqual); // true
});
});
That’s it about this short article. Hope you learned something new today
Don’t forget to subscribe to get my weekly newsletter with amazing tips, tricks, and articles directly in your inbox here.