Blog | G5 Cyber Security

Bcrypt Password Hashing

TL;DR

This guide shows you how to securely store passwords using Bcrypt with SHA-256 hashing. It covers generating salts, hashing passwords, and verifying them when a user logs in.

1. Understanding Password Hashing

Never store passwords directly! Hashing transforms the password into an unreadable string. Bcrypt adds salt to this process making it much harder for attackers to crack even if they get hold of your database.

2. Choosing a Library

Many programming languages have libraries that handle Bcrypt for you. Here are some examples:

We’ll use Python with the bcrypt library for this example, but the principles are similar in other languages.

3. Installing the Library

If you don’t have it already, install the Bcrypt library using pip:

pip install bcrypt

4. Generating a Salt

A salt is random data added to each password before hashing. This makes rainbow table attacks much less effective.

import bcrypt

salt = bcrypt.gensalt()
print(salt)

The gensalt() function generates a suitable salt. You don’t need to store the salt separately; it’s included in the hashed password.

5. Hashing the Password

Use the generated salt to hash the user’s password:

password = "mysecretpassword"
pwd_bytes = password.encode('utf-8')
hashed_password = bcrypt.hashpw(pwd_bytes, salt)
print(hashed_password)

The hashpw() function takes the password (encoded as bytes) and the salt as input and returns the hashed password.

6. Storing the Hashed Password

Store the hashed_password in your database. Do *not* store the original password!

7. Verifying the Password During Login

When a user tries to log in, compare the hashed version of their entered password with the stored hash:

entered_password = "mysecretpassword"
entered_pwd_bytes = entered_password.encode('utf-8')
stored_hash = b'$2b$12$EXAMPLEHASHEDPASSWORD'

if bcrypt.checkpw(entered_pwd_bytes, stored_hash):
    print("Password matches!")
else:
    print("Incorrect password.")

The checkpw() function compares the entered password (encoded as bytes) with the stored hash. It returns True if they match, and False otherwise.

8. Important Considerations

Exit mobile version