PYTHON
Secure Password Hashing and Verification with Bcrypt in Python
Learn to securely hash and verify user passwords in Python using the `bcrypt` library, protecting sensitive credentials against brute-force attacks and database breaches with salting.
import bcrypt
def hash_password(password):
"""Hashes a password using bcrypt."""
# Generate a salt and hash the password
# gensalt() generates a new salt for each password, increasing security
hashed_bytes = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
return hashed_bytes.decode('utf-8')
def verify_password(plain_password, hashed_password):
"""Verifies a plain password against a stored hashed password."""
# bcrypt.checkpw automatically extracts the salt from the hashed_password
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
# --- Example Usage ---
user_input_password = "mySecurePassword123"
# 1. Hash the password for storage
stored_hashed_password = hash_password(user_input_password)
print(f"Stored Hashed Password: {stored_hashed_password}")
# 2. Later, when a user tries to log in, verify their input
login_attempt_password = "mySecurePassword123"
if verify_password(login_attempt_password, stored_hashed_password):
print("Password verification successful!")
else:
print("Invalid password.")
# Test with a wrong password
wrong_password = "wrongPassword"
if verify_password(wrong_password, stored_hashed_password):
print("This should not print: Wrong password successful.")
else:
print("Correctly identified wrong password.")
How it works: This Python snippet demonstrates how to securely hash and verify passwords using the `bcrypt` library. Bcrypt is a strong hashing algorithm designed to be slow, making brute-force attacks computationally expensive. The `hash_password` function generates a unique salt for each password before hashing, preventing rainbow table attacks. The `verify_password` function then safely compares a plain-text password with its stored hash, handling the salt extraction automatically, ensuring passwords are never stored or compared in plain text.