PYTHON
Secure Password Hashing with Bcrypt in Python
Learn to securely hash and verify user passwords using the bcrypt library in Python, a critical step for protecting sensitive user data against breaches.
import bcrypt
def hash_password(password):
"""Hashes a password using bcrypt."""
# bcrypt.gensalt() generates a salt, making each hash unique
hashed_bytes = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
return hashed_bytes.decode('utf-8')
def verify_password(password, hashed_password):
"""Verifies a password against a stored hash."""
return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
# Example usage:
user_password = "MySuperSecretPassword123!"
stored_hash = hash_password(user_password)
print(f"Hashed password: {stored_hash}")
# Verify a correct password
if verify_password(user_password, stored_hash):
print("Password verified successfully!")
else:
print("Password verification failed.")
# Verify an incorrect password
incorrect_password = "WrongPassword"
if verify_password(incorrect_password, stored_hash):
print("Incorrect password verified (ERROR)!")
else:
print("Incorrect password correctly rejected.")
How it works: This snippet demonstrates how to use the `bcrypt` library in Python to securely hash and verify user passwords. `bcrypt.gensalt()` creates a unique salt for each password, preventing rainbow table attacks. The `hashpw` function performs the hashing, and `checkpw` safely compares a plain-text password to a stored hash without revealing the original password, protecting against brute-force and dictionary attacks.