**Password Hashing and Salting in Python** To protect a password from a password cracking system, you can use a combination of hashing and salting. Here's an example implementation in Python: ### Requirements * `hashlib` for hashing * `secrets` for generating cryptographically secure random numbers (for salting) ### Code ```python import hashlib import secrets import os def hash_password(password): """ Hash a password using SHA-256 and a random salt. Args: password (str): The password to hash. Returns: str: The hashed password. """ # Generate a random salt salt = secrets.token_bytes(16) # Hash the password with the salt hashed_password = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) # Return the salt and the hashed password as a single string return salt.hex() + ':' + hashed_password.hex() def verify_password(stored_password, provided_password): """ Verify a password against a stored hashed password. Args: stored_password (str): The stored hashed password. provided_password (str): The password to verify. Returns: bool: True if the password is valid, False otherwise. """ # Split the stored password into salt and hashed password salt, stored_hashed_password = stored_password.split(':') # Generate the same salt salt = bytes.fromhex(salt) # Hash the provided password with the same salt provided_hashed_password = hashlib.pbkdf2_hmac('sha256', provided_password.encode('utf-8'), salt, 100000) # Return True if the hashed passwords match, False otherwise return provided_hashed_password.hex() == stored_hashed_password # Example usage password = "mysecretpassword" hashed_password = hash_password(password) print("Hashed password:", hashed_password) # Verify the password is_valid = verify_password(hashed_password, password) print("Is password valid?", is_valid) ``` ### Explanation 1. The `hash_password` function generates a random salt using `secrets.token_bytes` and hashes the password using `hashlib.pbkdf2_hmac`. The salt and hashed password are returned as a single string. 2. The `verify_password` function takes a stored hashed password and a provided password, splits the stored password into salt and hashed password, and hashes the provided password with the same salt. It returns True if the hashed passwords match, False otherwise. 3. In the example usage, a password is hashed and stored, and then verified against the stored hashed password. ### Security Considerations * Use a secure random number generator (e.g., `secrets`) to generate the salt. * Use a strong hashing algorithm (e.g., SHA-256) and a sufficient number of iterations (e.g., 100000). * Store the salt and hashed password securely, e.g., in a database with proper access controls. * Use a secure password verification process, e.g., by comparing the hashed passwords directly rather than storing the original password.
Please keep input under 1000 characters