Hashing Passwords in Python with BCrypt

Password hashing is a technique used to store passwords securely. It involves converting plain text passwords into a hashed format that cannot be easily reversed or decrypted. By hashing passwords, even if a hacker gains access to the password database, they will not be able to decipher the passwords.

BCrypt is a password hashing algorithm that is considered one of the most secure algorithms for password hashing in Python. BCrypt is designed to be slow, which makes it more difficult for hackers to crack the hashed passwords.

Installation

First, install the BCrypt library using pip:

pip install bcrypt

Syntax

The basic syntax for hashing passwords with BCrypt:

import bcrypt
hashed_password = bcrypt.hashpw(password, salt)

Here, password is the user-submitted string and salt is a random text appended to the password to store it even more securely. The hashpw function encrypts the password and can be used later to authenticate users.

Key BCrypt Functions

hashpw(password, salt)

This method hashes the password using the salt provided. It returns a hashed password that can be stored in a database.

bcrypt.hashpw(password, salt)

Parameters:

  • password ? The password to be hashed as a byte string.

  • salt ? The salt to be used in the hashing process. This should also be a byte string.

gensalt(rounds=12)

This method generates a random salt that can be used in the password hashing process. It returns the salt as a byte string.

bcrypt.gensalt(rounds=12)

Parameters:

  • rounds ? The number of rounds to use in the hashing process. Security of the hash is directly correlated to the number of rounds. The default value is 12, and it is recommended to use a value between 10 and 15.

checkpw(password, hashed_password)

This method checks if the plain text password matches the hashed password. It returns a Boolean value.

bcrypt.checkpw(password, hashed_password)

Parameters:

  • password ? The plain text password to be checked.

  • hashed_password ? The hashed password to be compared against.

Hashing Process Algorithm

  • Generate a random salt using BCrypt's built-in gensalt() function.

  • Combine the plain text password with the salt.

  • Hash the combination using BCrypt's hashpw() function.

  • Store the hashed password in the password database.

The importance of adding salt to the hashed password cannot be overstated. Salt is a random string of characters that is unique for each user, making it impossible for hackers to use precomputed rainbow tables to crack passwords.

Basic Password Hashing Example

import bcrypt

password = b"password123"
salt = bcrypt.gensalt(rounds=12)
hashed_password = bcrypt.hashpw(password, salt)
print("Original password:", password.decode())
print("Hashed password:", hashed_password.decode())
Original password: password123
Hashed password: $2b$12$9gYgEJm.PQKjWgQ8JZXm1eGvKvKZrIrQ3V9LKRrHlCJ7LZ8pGQm5G

Password Verification Example

import bcrypt

password = b"password123"
salt = bcrypt.gensalt(rounds=12)
hashed_password = bcrypt.hashpw(password, salt)

# Verify correct password
if bcrypt.checkpw(password, hashed_password):
    print("Password is correct")
else:
    print("Password is incorrect")

# Verify wrong password
wrong_password = b"wrongpassword"
if bcrypt.checkpw(wrong_password, hashed_password):
    print("Wrong password is correct")
else:
    print("Wrong password is incorrect")
Password is correct
Wrong password is incorrect

Complete User Authentication System

import bcrypt

class UserAuth:
    def __init__(self):
        self.users = {}
    
    def register_user(self, username, password):
        # Hash the password
        salt = bcrypt.gensalt(rounds=12)
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
        self.users[username] = hashed_password
        print(f"User {username} registered successfully")
    
    def authenticate_user(self, username, password):
        if username in self.users:
            stored_hash = self.users[username]
            if bcrypt.checkpw(password.encode('utf-8'), stored_hash):
                print(f"Authentication successful for {username}")
                return True
            else:
                print(f"Authentication failed for {username}")
                return False
        else:
            print(f"User {username} not found")
            return False

# Example usage
auth_system = UserAuth()
auth_system.register_user("john_doe", "mySecurePassword123")
auth_system.authenticate_user("john_doe", "mySecurePassword123")
auth_system.authenticate_user("john_doe", "wrongPassword")
User john_doe registered successfully
Authentication successful for john_doe
Authentication failed for john_doe

Applications

Password hashing is an essential security measure used by applications including:

  • Online banking systems

  • E-commerce websites

  • Social networking sites

  • Web applications requiring user authentication

Conclusion

BCrypt provides a secure and reliable method for hashing passwords in Python applications. By using proper salting and configurable round counts, BCrypt ensures that even if your database is compromised, user passwords remain protected. Always use BCrypt's checkpw() function for password verification rather than comparing hashes directly.

Updated on: 2026-03-27T01:17:30+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements