← Back to all snippets
PYTHON

Securely Hash User Passwords with Bcrypt in Python

Learn to securely store user passwords in Python using the `bcrypt` library. Bcrypt provides strong, adaptive hashing, crucial for protecting sensitive user data.

import bcrypt

def hash_password(password: str) -> str:
    """Hashes a plaintext password using bcrypt."""
    # Generate a salt and hash the password
    # bcrypt.gensalt() generates a new salt with a default rounds value (12)
    # Higher rounds (cost) means more work, but slower hashing. Adjust based on hardware.
    hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    return hashed.decode('utf-8')

def check_password(password: str, hashed_password: str) -> bool:
    """Checks if a plaintext password matches a bcrypt hashed password."""
    return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))

# Example Usage:
user_password = "mySuperSecretPassword123!"

# 1. Hash the password for storage
stored_hash = hash_password(user_password)
print(f"Original password: {user_password}")
print(f"Stored hash: {stored_hash}")

# 2. When user logs in, check their provided password against the stored hash
login_attempt_correct = "mySuperSecretPassword123!"
login_attempt_incorrect = "wrongPassword"

if check_password(login_attempt_correct, stored_hash):
    print(f"'{login_attempt_correct}' matches the stored hash. Login successful!")
else:
    print(f"'{login_attempt_correct}' does NOT match. Login failed.")

if check_password(login_attempt_incorrect, stored_hash):
    print(f"'{login_attempt_incorrect}' matches the stored hash. Login successful!")
else:
    print(f"'{login_attempt_incorrect}' does NOT match. Login failed.")
How it works: This Python snippet demonstrates how to securely hash user passwords using the `bcrypt` library. The `hash_password` function generates a unique salt for each password and then hashes it with `bcrypt.hashpw`. Bcrypt is a computationally intensive algorithm designed to resist brute-force attacks. The `check_password` function safely verifies a provided plaintext password against a stored hash without re-hashing or exposing the original password, making it suitable for authentication.

Need help integrating this into your project?

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

Hire DigitalCodeLabs