PYTHON

Secure Password Hashing with Werkzeug (Python)

Implement robust password hashing in Python using Flask's Werkzeug security utilities, ensuring strong, salted, and adaptive protection against brute-force attacks.

from werkzeug.security import generate_password_hash, check_password_hash

class User:
    def __init__(self, username, password):
        self.username = username
        # Hash the password during user creation
        self.password_hash = self._hash_password(password)

    def _hash_password(self, password):
        # generate_password_hash uses PBKDF2 by default, with a random salt and configurable iterations.
        # The method stores the algorithm, salt, and hash in one string for easy storage.
        return generate_password_hash(password)

    def check_password(self, password):
        # check_password_hash correctly extracts the salt and algorithm
        # from the stored hash to verify the provided password without re-hashing the stored one.
        return check_password_hash(self.password_hash, password)

# --- Usage Example --- 
# Registering a new user
new_user = User('alice', 'securePassword123')
print(f"Stored hash for alice: {new_user.password_hash}")

# Verifying a password during login
if new_user.check_password('securePassword123'):
    print("Alice logged in successfully!")
else:
    print("Incorrect password for Alice.")

# Trying a wrong password
if new_user.check_password('wrongPassword'):
    print("This should not happen.")
else:
    print("Wrong password handled correctly.")
How it works: This Python snippet demonstrates secure password hashing using `werkzeug.security` (a common dependency in Flask applications). Instead of storing plain text passwords, `generate_password_hash()` creates a secure hash using a strong, modern algorithm (like PBKDF2), a unique random salt, and configurable iterations. The salt and algorithm details are securely embedded within the resulting hash string. `check_password_hash()` then verifies a provided password against a stored hash, correctly extracting the necessary parameters. This method prevents rainbow table attacks and makes brute-forcing significantly harder, a crucial aspect of user data security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs