← Back to all snippets
PYTHON

Secure Password Hashing with bcrypt

Learn to securely hash and verify user passwords using the bcrypt library in Python, protecting against common credential theft attacks by storing hashes instead of plain text.

import bcrypt

def hash_password(password):
    """Hashes a password using bcrypt."""
    # bcrypt.gensalt() generates a random salt
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    return hashed_password.decode('utf-8')

def check_password(password, hashed_password):
    """Checks if a password matches a given hash."""
    return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))

# Example Usage:
user_password = "mySecretPassword123"
hashed = hash_password(user_password)
print(f"Hashed Password: {hashed}")

# Later, during login:
is_correct = check_password("mySecretPassword123", hashed)
print(f"Password correct? {is_correct}")

is_incorrect = check_password("wrongPassword", hashed)
print(f"Wrong password correct? {is_incorrect}")
How it works: This snippet demonstrates how to use the `bcrypt` library in Python to securely hash and verify user passwords. Instead of storing plain-text passwords, which is highly insecure, `bcrypt` generates a unique salt for each password and applies a computationally intensive hashing algorithm. This makes it extremely difficult for attackers to reverse-engineer passwords even if they gain access to your database, preventing rainbow table attacks and mitigating brute-force attempts by design.

Need help integrating this into your project?

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

Hire DigitalCodeLabs