PYTHON

Secure Password Hashing with Argon2 for User Authentication

Learn to securely hash user passwords using the Argon2 algorithm, protecting sensitive credentials with robust key derivation functions.

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

# Initialize the PasswordHasher with recommended parameters
# time_cost: number of iterations, memory_cost: memory usage in KiB, parallelism: number of threads
ph = PasswordHasher(
    time_cost=2,      # Number of iterations
    memory_cost=65536,  # Memory usage (KiB)
    parallelism=1     # Number of threads
)

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

def verify_password(hashed_password, plain_password):
    """Verifies a plain-text password against a hashed password."""
    try:
        ph.verify(hashed_password, plain_password)
        # If the hash needs re-hashing due to updated parameters (e.g., increased cost)
        if ph.check_needs_rehash(hashed_password):
            print("Password hash needs re-hashing with updated parameters.")
            # You would typically re-hash and update the stored hash in the database here.
        return True
    except VerifyMismatchError:
        return False
    except Exception as e:
        print(f"An error occurred during password verification: {e}")
        return False

# --- Example Usage ---
user_password = "MySecurePassword123!"

# 1. Hash the password for storage
hashed_pwd = hash_password(user_password)
print(f"Hashed Password: {hashed_pwd}")

# 2. Verify a correct password
is_valid = verify_password(hashed_pwd, user_password)
print(f"Is '{user_password}' valid? {is_valid}")

# 3. Verify an incorrect password
is_invalid = verify_password(hashed_pwd, "WrongPassword")
print(f"Is 'WrongPassword' valid? {is_invalid}")

# Example of a re-hash scenario (conceptually)
# If `ph` parameters were changed (e.g., memory_cost increased),
# `check_needs_rehash` would return True.
How it works: Storing plain-text passwords is a major security vulnerability. This snippet demonstrates how to securely hash user passwords using Argon2, a robust key derivation function chosen as the winner of the Password Hashing Competition. It uses the `argon2-cffi` library in Python to hash a password with configurable parameters (cost factors) and then verify a given plain-text password against the stored hash. Argon2 is designed to be resistant to brute-force and rainbow table attacks due to its computational intensity and configurable memory usage.

Need help integrating this into your project?

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

Hire DigitalCodeLabs