← Back to all snippets
PYTHON

Securely Hash Passwords Using Hashing Algorithms

Learn to securely hash user passwords in Python using modern, robust algorithms like bcrypt, critical for protecting user credentials against breaches.

import bcrypt

def hash_password(password):
    """Hashes a password using bcrypt."""
    # Generate a salt and hash the password
    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."""
    # Verify the password
    return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))

# Usage example:
user_password = "MyS3cr3tP@ssw0rd!"

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

# Verify a correct password
is_valid = verify_password(user_password, stored_hash)
print(f"Verification with correct password: {is_valid}")

# Verify an incorrect password
is_invalid = verify_password("WrongP@ssw0rd", stored_hash)
print(f"Verification with incorrect password: {is_invalid}")
How it works: This Python snippet demonstrates how to securely hash and verify user passwords using the `bcrypt` library. Bcrypt is a strong, adaptive hashing algorithm designed to be slow, making brute-force attacks computationally intensive. It automatically generates a unique salt for each password, preventing rainbow table attacks. The `hash_password` function generates a new hash, and `verify_password` checks a provided password against a stored hash without exposing the original password.

Need help integrating this into your project?

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

Hire DigitalCodeLabs