PYTHON

Secure Password Hashing with Argon2

Learn to securely hash user passwords using the Argon2 algorithm in Python, protecting sensitive credentials from brute-force attacks and rainbow tables with robust cryptographic techniques.

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

# Initialize the password hasher
# It's recommended to store parameters (time_cost, memory_cost, parallelism)
# as environment variables or configuration for production.
ph = PasswordHasher(
    time_cost=2,      # Number of iterations
    memory_cost=65536, # Memory usage in kibibytes (64MB)
    parallelism=1,    # Number of threads
    hash_len=16,      # Length of the derived key
    salt_len=16       # Length of the salt
)

def hash_password(password: str) -> str:
    """Hashes a plain-text password using Argon2."""
    return ph.hash(password)

def verify_password(hashed_password: str, plain_password: str) -> bool:
    """Verifies a plain-text password against a hashed password."""
    try:
        ph.verify(hashed_password, plain_password)
        return True
    except VerifyMismatchError:
        return False
    except Exception as e:
        # Handle other potential errors during verification (e.g., malformed hash)
        print(f"An error occurred during password verification: {e}")
        return False

if __name__ == "__main__":
    user_input_password = "MySuperSecurePassword123!"

    # Hash the password for storage
    hashed = hash_password(user_input_password)
    print(f"Original password: {user_input_password}")
    print(f"Hashed password (store this): {hashed}")

    # Later, verify a login attempt
    login_attempt_password_correct = "MySuperSecurePassword123!"
    login_attempt_password_incorrect = "WrongPassword123"

    if verify_password(hashed, login_attempt_password_correct):
        print("Verification successful! User logged in.")
    else:
        print("Verification failed. Incorrect password.")

    if verify_password(hashed, login_attempt_password_incorrect):
        print("Verification successful! (This should not happen)")
    else:
        print("Verification failed. Incorrect password (as expected).")

# To run this:
# 1. pip install argon2-cffi
# 2. Save as password_hasher.py and run python password_hasher.py
How it works: This Python snippet demonstrates how to securely hash and verify user passwords using the Argon2 algorithm via the `argon2-cffi` library. Argon2 is an industry-recommended algorithm designed to be resistant against brute-force attacks and rainbow table lookups, primarily by being computationally expensive in terms of time and memory. The `PasswordHasher` class is initialized with configurable costs (time, memory, parallelism) and salt/hash lengths. The `hash_password` function takes a plain-text password and returns its secure hash for storage, while `verify_password` checks if a provided plain-text password matches a stored hash. This approach is crucial for protecting sensitive user credentials, even if a database breach occurs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs