sec-password-hashing
0.500
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
# solution.py
import hashlib
import os
import binascii
def hash_password(password: str) -> str:
# Generate a random salt
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
# Hash the password with the salt using PBKDF2
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
# Combine salt and hash for storage
hashed = salt + pwdhash
# Return as a hex string
return binascii.hexlify(hashed).decode('ascii')
def verify_password(password: str, hashed: str) -> bool:
# Decode the hex string to get salt and hash
hashed_bytes = binascii.unhexlify(hashed.encode('ascii'))
# Extract salt (first 64 bytes) and stored hash (remaining bytes)
salt = hashed_bytes[:64]
stored_hash = hashed_bytes[64:]
# Hash the provided password with the extracted salt
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
# Compare the computed hash with the stored hash
return pwdhash == stored_hash
```