← run

sec-password-hashing

1.000
2/2 tests· security

Proposed solution

```python
import hashlib
import secrets

def hash_password(password: str) -> str:
    """Hash a password for storing."""
    # Generate a random salt
    salt = secrets.token_hex(16)
    
    # Hash the password with the salt
    pwdhash = hashlib.pbkdf2_hmac('sha256',
                                            password.encode('utf-8'),
                                            salt.encode('utf-8'),
                                            100000)
    
    # Return salt and hash combined
    return salt + pwdhash.hex()

def verify_password(password: str, hashed: str) -> bool:
    """Verify a stored password against its hash."""
    # Extract the salt (first 32 characters)
    salt = hashed[:32]
    
    # Extract the hash (remaining characters)
    stored_hash = hashed[32:]
    
    # Hash the provided password with the extracted salt
    pwdhash = hashlib.pbkdf2_hmac('sha256',
                                  password.encode('utf-8'),
                                  salt.encode('utf-8'),
                                  100000)
    
    # Compare the hashes
    return pwdhash.hex() == stored_hash
```