Learn to Protect Passwords with Bcrypt Hash in a Few Minutes
Tags: webdev, security, programming, beginners
Published: 2023-08-09 08:32:14


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](https://en.m.wikipedia.org/wiki/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] (https://en.m.wikipedia.org/wiki/Brute-force_attack) and [rainbow table attacks](https://en.m.wikipedia.org/wiki/Rainbow_table). 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](https://en.m.wikipedia.org/wiki/Niels_Provos) and [David Mazières](https://www.scs.stanford.edu/~dm/home/bio.html), 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] (https://en.m.wikipedia.org/wiki/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.

```bash
npm install bcrypt
```

We then include the `bcrypt` module in our code.

```javascript
const bcrypt = require("bcrypt")
```

Now `bcrypt` has several methods, and we can choose to perform our hash synchronously or asynchronously. You can find documentation for [npm bcrypt]  (https://www.npmjs.com/package/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.

```javascript
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) 
}
```
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. 

```javascript
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
}
```
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.

```javascript
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
}
```
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.