PYTHON

Secure Password Hashing with Argon2 in Python

Implement strong password hashing using Argon2 in Python for robust security, protecting user credentials from dictionary attacks and rainbow tables.

import argon2

def hash_password(password):
    # Using argon2-cffi library
    hasher = argon2.PasswordHasher()
    hashed_password = hasher.hash(password)
    return hashed_password

def verify_password(hashed_password, provided_password):
    hasher = argon2.PasswordHasher()
    try:
        hasher.verify(hashed_password, provided_password)
        # If verification is successful, rehash if parameters changed (e.g., cost factor)
        if hasher.check_needs_rehash(hashed_password):
            # In a real application, you would rehash and update the stored hash here
            print("Password needs re-hashing with updated parameters.")
        return True
    except argon2.exceptions.VerifyMismatchError:
        return False
    except Exception as e:
        print(f"An error occurred during password verification: {e}")
        return False

# Example usage:
# password = "mysecretpassword123"
# hashed_pw = hash_password(password)
# print(f"Hashed password: {hashed_pw}")
# print(f"Verification success: {verify_password(hashed_pw, password)}") # True
# print(f"Verification fail: {verify_password(hashed_pw, 'wrongpassword')}") # False
How it works: This Python snippet demonstrates secure password hashing using the `argon2-cffi` library. Argon2 is a modern, memory-hard key derivation function recommended by the Password Hashing Competition. The `hash_password` function takes a plain-text password and returns a securely hashed string. The `verify_password` function compares a provided password against a stored hash. It also includes a `check_needs_rehash` mechanism to prompt for updating hashes if the hashing parameters (like memory or time cost) have been strengthened, ensuring ongoing security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs