DEV Community

Cover image for Learn to Protect Passwords with Bcrypt Hash in a Few Minutes
Stephen Odogwu
Stephen Odogwu

Posted on • Edited on

Learn to Protect Passwords with Bcrypt Hash in a Few Minutes

Whenever we put in our details to register on any website, attackers are always on the lookout to steal our details. We hear terms like encoding and encryption, but they can never be like the Bcrypt hash format, where we hash passwords with bcrypt. Lately I have been working on the backend and one password protection tool I always see and have come to really love and understand is bcrypt.

In this article we specify the differences between encryption, encoding and hashing, we also go to the bone of contention which is how to create a bcrypt password hash.

Differences Between Encryption, Encoding and Hashing

We now take a look at the three data protection practices commonly used, this helps us to know the differences between them.

Encryption

This is basically a method of securing data to make it unreadable by using an algorithm and a key. The drawback with Encryption is that it is reversible.The original data can be retrieved with the right decryption key.

Encoding

Encoding is mainly done for system compatibility and not for protection, even though it converts data to a different format so that it can be stored on certain systems but definitely not for protection against hackers.

Hashing

The main difference between a hashed password and an encrypted one is that hashing only works one way and cannot be reversed, so you can hash a password but cannot un-hash it, unlike encryption that can be decrypted through brute force attacks and rainbow table attacks. So to minimize these, we add salt to the password before it is hashed. The salt is randomly generated data that is added to your password to make sure it is unique.

What is Bcrypt

Bcrypt is a short form for "Blowfish-crypt ". It is a cryptographic algorithm designed for password hashing. Not all hash algorithms are the same, and there are many options available. It was developed by Niels Provos and David Mazières, to address vulnerabilities and weaknesses found in other hash functions.

Bcrypt is widely recognized as a secure and reliable choice for password hashing. It is a password hashing function.

How does Bcrypt Work?

The salt is a major ingredient in this process. The salt helps mitigate against brute force attacks and rainbow table attacks. Bcrypt uses the blowfish cypher which is slow enough and mitigates the limitations of the SHA functions which are designed to be computationally fast.

If a hash password is calculated or generated with too much speed, the faster brute force attacks can get through, so we use the bcrypt hash format to protect against this. Bcrypt is used across various programming languages, but in this article I will be concentrating on Node.js because that is what I use.

Password Hashing in Node.js With Bcrypt

We know that to use Bcrypt we first need to install the library.

npm install bcrypt
Enter fullscreen mode Exit fullscreen mode

We then include the bcrypt module in our code.

const bcrypt = require("bcrypt")
Enter fullscreen mode Exit fullscreen mode

Now bcrypt has several methods, and we can choose to perform our hash synchronously or asynchronously. You can find documentation for npm bcrypt.
However as a personal preference I like to use the asynchronous method, async await precisely.

Example of Password Hashing With Bcrypt in Node.js

Suppose we are making an online registration form where users are required to input their emails and passwords.

async function register(email, password){
/*We know salt is needed to hash our passwords,let's create it*/

const saltRounds = 10
const salt = await bcrypt.genSalt(saltRounds)

/*we now have our salt, we use it to hash our password with the hash method*/
const hashedPassword= await bcrypt.hash(password,salt) 
}
Enter fullscreen mode Exit fullscreen mode

Now we have our hashed password as hashedPassword. Suppose we have a User model made with mongoose for a Mongodb database, which we want to create documents from, where document properties are email and password which will be taken from client input. We can now pass the hashedPassword as value of password, like below.

async function register(email, password){
const saltRounds = 10
const salt = await bcrypt.genSalt(saltRounds)
const hashedPassword=await bcrypt.hash(password,salt) 
//create user 
const user = await User.create({email, password: hashedPassword})
return user
}
Enter fullscreen mode Exit fullscreen mode

It is a very easy to understand package, so straightforward.
Now let's assume the above to be a sign-up function.

We could also utilize it for a login function. Assume we have the same User model which we used above. We could use the bcrypt.compare method.

async function login(email,password){
if(!email||!password){
    throw Error("All fields must be filled")
}
// check if user exists via email
const user=await this.findOne({email})
if(!user){
    throw Error('incorrect login details')
}
//via password
let match=await bcrypt.compare(password,user.password) //where user.password is hashed password

if(!match){
    throw Error('incorrect login details')
}
return user
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we compared the initial password that must have been input from client side with user.password, as we saw above, user.password is now hashedPassword from the first register function where we passed hashedPassword as value of password in our user document. If there is a match as a result of bcrypt.compare, only then can the user login, otherwise it is assumed that they haven't previously signed up because signing up automatically hashes the password.

Takeaways

For security purposes,it is necessary to hash passwords before storing them in a secure database

Before hashing a password we apply salt. A salt is a random string that makes the hash unpredictable.

saltRounds: The number of times the hashing function is added to the password and salt combination. An increase in the number makes the time and resources that will be required to crack the password more. So a saltRound of 11 for instance will take longer to crack than a 10.

Top comments (4)

Collapse
 
phlash profile image
Phil Ashby

Thanks for this concise and valid guide to hashing passwords for storage 🙏

I would like to add that along with a secure storage mechanism, managing passwords (and thus access to your service) locally also needs a well-thought-out set of password reset and recovery flows, possibly involving call centre humans and other factors outside the software. The majority of access control failings are due to these processes being easier to attack (eg via social engineering) than the technology.

Collapse
 
kellyescobar profile image
KellyEscobar

Thanks post. I have learning protected files. dua to make someone love you

Collapse
 
rishabhjaincodes profile image
Rishabh Jain

Wow this is just amazing article to read and learn. Thanks !!!

Collapse
 
soanvig profile image
Mateusz Koteja • Edited

Salt doesn't protect against brute force. That's because it is public. Only protects against rainbow tables.