PYTHON
Securely Hash and Verify User Passwords with bcrypt
Learn how to securely hash and verify user passwords in Python using the bcrypt library, protecting sensitive credentials from brute-force and rainbow table attacks.
import bcrypt
def hash_password(password):
# Generate a salt and hash the password
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
return hashed_password.decode('utf-8')
def verify_password(password, hashed_password):
# Verify a password against a stored hash
return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
# Example Usage:
# user_password = "mySecretPassword123"
# stored_hash = hash_password(user_password)
# print(f"Hashed Password: {stored_hash}")
#
# # Later, when user tries to log in:
# login_attempt_password = "mySecretPassword123"
# if verify_password(login_attempt_password, stored_hash):
# print("Password verified successfully!")
# else:
# print("Invalid password.")
#
# login_attempt_wrong_password = "wrongPassword"
# if verify_password(login_attempt_wrong_password, stored_hash):
# print("This should not happen.")
# else:
# print("Incorrect password detected.")
How it works: This Python snippet demonstrates how to use the `bcrypt` library to securely hash and verify user passwords. `bcrypt.gensalt()` generates a unique salt for each password, which is then incorporated into the hash. This prevents rainbow table attacks. `bcrypt.hashpw()` performs the hashing, and `bcrypt.checkpw()` safely compares a provided password against a stored hash, handling the salt and stretching automatically.