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 secrets
import base64
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
pwd_hash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100_000)
return f"pbkdf2_sha256${base64.b64encode(salt).decode('ascii')}${base64.b64encode(pwd_hash).decode('ascii')}"
def verify_password(password: str, hashed: str) -> bool:
try:
algo, salt_b64, hash_b64 = hashed.split('$')
if algo != 'pbkdf2_sha256':
return False
salt = base64.b64decode(salt_b64)
pwd_hash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100_000)
return base64.b64encode(pwd_hash).decode('ascii') == hash_b64
except Exception:
return False
```