← Back to all snippets
PYTHON

Securely Hash and Verify Passwords with Python Bcrypt

Learn to implement strong password security in Python applications using the `bcrypt` library for hashing and verifying passwords, protecting user credentials effectively.

import bcrypt

def hash_password(password):
    """Hashes a password using bcrypt."""
    # Generate a salt and hash the password
    # bcrypt.gensalt() generates a random salt.
    # bcrypt.hashpw() returns bytes, so decode to utf-8 for storage.
    hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    return hashed.decode('utf-8')

def verify_password(password, hashed_password):
    """Verifies a password against a stored hash."""
    # hashpw requires bytes for both password and the stored hash
    return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))

# Example Usage:
user_password = "MySuperSecretPassword123!"

# 1. Hash the password
stored_hashed_password = hash_password(user_password)
print(f"Original Password: {user_password}")
print(f"Hashed Password (stored in DB): {stored_hashed_password}")

# 2. Verify a correct password
if verify_password(user_password, stored_hashed_password):
    print("Password verification SUCCESS: Correct password provided.")
else:
    print("Password verification FAILED: Incorrect password provided.")

# 3. Verify an incorrect password
wrong_password = "WrongPassword!"
if verify_password(wrong_password, stored_hashed_password):
    print("Password verification FAILED: Incorrect password was accepted (ERROR!).")
else:
    print("Password verification SUCCESS: Incorrect password rejected.")

# Note: Stored hashes are unique even for the same password due to the random salt.
another_hash = hash_password(user_password)
print(f"Another hash for the same password: {another_hash}")
How it works: This Python snippet demonstrates how to securely hash and verify passwords using the `bcrypt` library. `bcrypt` is a strong, adaptive hashing algorithm designed to resist brute-force attacks by being computationally intensive. The `hash_password` function generates a random salt and hashes the provided password, ensuring that even identical passwords result in different hashes. The `verify_password` function then safely compares a given password against a stored hash, handling the salt and hashing internally.

Need help integrating this into your project?

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

Hire DigitalCodeLabs