PYTHON

Secure Password Hashing and Verification with Python's bcrypt

Learn to securely hash and verify user passwords in Python applications using the robust `bcrypt` library, crucial for protecting sensitive user data.

import bcrypt

def hash_password(password):
    """Hashes a password using bcrypt."""
    hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    return hashed.decode('utf-8')

def verify_password(password, hashed_password):
    """Verifies a plain-text password against a hashed password."""
    return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))

# Example Usage:
user_password = "mySuperSecretPassword123!"

# Hash the password for storage
stored_hash = hash_password(user_password)
print(f"Original Password: {user_password}")
print(f"Hashed Password: {stored_hash}")

# Verify a password later
is_correct = verify_password("mySuperSecretPassword123!", stored_hash)
print(f"Password verification (correct): {is_correct}")

is_incorrect = verify_password("wrongPassword", stored_hash)
print(f"Password verification (incorrect): {is_incorrect}")
How it works: This Python snippet illustrates how to securely hash and verify passwords using the `bcrypt` library. `bcrypt.gensalt()` generates a unique salt for each password, which is then combined with the password and hashed using `bcrypt.hashpw()`. The resulting hash includes the salt and algorithm parameters, making it resistant to rainbow table attacks. `bcrypt.checkpw()` safely compares a plain-text password with a stored hash, handling the salting and hashing internally for verification.

Need help integrating this into your project?

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

Hire DigitalCodeLabs