sec-password-hashing
1.000
Challenge · difficulty 3/5
# Task Implement **`solution.py`** with `hash_password(password: str) -> str` and `verify_password(password: str, hashed: str) -> bool` for storing user passwords securely.
Proposed solution
```python
import hashlib
import os
def hash_password(password: str) -> str:
"""
Hash a password using PBKDF2-HMAC-SHA256 with a random salt.
Args:
password: The plain text password to hash
Returns:
A string containing the salt and hash separated by ':'
"""
salt = os.urandom(32) # 256-bit random salt
password_bytes = password.encode('utf-8')
hashed = hashlib.pbkdf2_hmac(
'sha256',
password_bytes,
salt,
100000, # iterations
dklen=32
)
# Combine salt and hash for storage
return salt.hex() + ':' + hashed.hex()
def verify_password(password: str, hashed: str) -> bool:
"""
Verify a password against its stored hash.
Args:
password: The plain text password to verify
hashed: The stored hash (salt:hash format)
Returns:
True if the password matches the hash, False otherwise
"""
try:
salt_hex, hash_hex = hashed.split(':')
salt = bytes.fromhex(salt_hex)
expected_hash = bytes.fromhex(hash_hex)
password_bytes = password.encode('utf-8')
computed_hash = hashlib.pbkdf2_hmac(
'sha256',
password_bytes,
salt,
100000, # same iterations as used during hashing
dklen=32
)
return computed_hash == expected_hash
except Exception:
return False
```