PYTHON

Securely Hashing Passwords with bcrypt in Python (Flask)

Learn to securely hash and verify user passwords using the `bcrypt` algorithm in Python web applications, preventing data breaches and enhancing security.

from werkzeug.security import generate_password_hash, check_password_hash

# Simulating user registration
def register_user(username, plain_password):
    # Hash the plain password before storing it
    hashed_password = generate_password_hash(plain_password, method='bcrypt')
    print(f"User '{username}' registered. Hashed password: {hashed_password}")
    return hashed_password

# Simulating user login
def login_user(username, entered_password, stored_hashed_password):
    # Verify the entered password against the stored hash
    if check_password_hash(stored_hashed_password, entered_password):
        print(f"User '{username}' logged in successfully!")
        return True
    else:
        print(f"Login failed for '{username}'. Invalid credentials.")
        return False

# --- Example Usage ---

# 1. Register a user
user_password = "myStrongP@ssw0rd!"
stored_hash = register_user("alice", user_password)

print("
--- Attempting logins ---")

# 2. Attempt successful login
login_user("alice", user_password, stored_hash)

# 3. Attempt failed login (wrong password)
login_user("alice", "wrongpassword", stored_hash)

# 4. Attempt failed login (different hash, simulating another user or db error)
login_user("bob", "myStrongP@ssw0rd!", generate_password_hash("anotherPassword", method='bcrypt'))
How it works: This Python snippet demonstrates how to securely hash and verify user passwords using the `werkzeug.security` module (commonly used in Flask applications), which leverages the `bcrypt` algorithm. `generate_password_hash()` takes a plain-text password and returns a strong, salted, and hashed version, which should be stored in the database. `check_password_hash()` compares an entered plain-text password against a stored hash, returning `True` if they match. `bcrypt` is designed to be slow and computationally intensive, making brute-force attacks on stolen password hashes very difficult, significantly enhancing security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs