PYTHON

Securely Hashing Passwords with Bcrypt in Python

Protect user passwords by implementing strong, one-way hashing using the `bcrypt` library in Python, crucial for preventing credential leaks and enhancing authentication security.

import bcrypt

def hash_password(password):
    """Hashes a password using bcrypt."""
    # Generate a salt and hash the password
    # gensalt() generates a salt with a default cost of 12
    hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    return hashed.decode('utf-8')

def check_password(password, hashed_password):
    """Checks if a plain-text password matches a bcrypt hashed password."""
    try:
        return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
    except ValueError:
        # Handle cases where the hashed_password might be malformed
        return False

# --- Example Usage ---

# 1. User signs up: Hash their password before storing
user_password = "MySuperSecurePassword123"
hashed_stored_password = hash_password(user_password)
print(f"Original password: {user_password}")
print(f"Hashed password (for storage): {hashed_stored_password}")

# 2. User logs in: Verify their entered password against the stored hash
login_attempt_correct = "MySuperSecurePassword123"
login_attempt_incorrect = "WrongPassword"

is_correct = check_password(login_attempt_correct, hashed_stored_password)
print(f"Login attempt with correct password: {is_correct}")

is_incorrect = check_password(login_attempt_incorrect, hashed_stored_password)
print(f"Login attempt with incorrect password: {is_incorrect}")

# Demonstrate hashing the same password twice yields different hashes due to salt
print(f"New hash for same password: {hash_password(user_password)}")
How it works: This Python snippet illustrates the secure way to handle user passwords using the `bcrypt` library. Storing passwords in plain text is a critical security vulnerability. Bcrypt solves this by performing a one-way cryptographic hash of the password combined with a randomly generated 'salt' and an adaptive 'cost' factor (work factor). This makes rainbow table attacks ineffective and brute-force attacks computationally expensive, even if the database is compromised. The `hash_password` function generates a unique hash for each password, and `check_password` verifies an entered password against a stored hash, ensuring secure authentication without ever exposing the actual password.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs