← run

sec-password-hashing

1.000
2/2 tests· security
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
import base64

ITERATIONS = 100_000
SALT_SIZE = 16
HASH_SIZE = 32


def hash_password(password: str) -> str:
    salt = os.urandom(SALT_SIZE)
    dk = hashlib.pbkdf2_hmac(
        'sha256',
        password.encode('utf-8'),
        salt,
        ITERATIONS,
        dklen=HASH_SIZE,
    )
    return (
        f"pbkdf2_sha256${ITERATIONS}$"
        f"{base64.b64encode(salt).decode('ascii')}"
        f"${base64.b64encode(dk).decode('ascii')}"
    )


def verify_password(password: str, hashed: str) -> bool:
    try:
        algorithm, iterations_str, salt_b64, hash_b64 = hashed.split('$')
        if algorithm != 'pbkdf2_sha256':
            return False
        iterations = int(iterations_str)
        salt = base64.b64decode(salt_b64)
        expected_hash = base64.b64decode(hash_b64)
        dk = hashlib.pbkdf2_hmac(
            'sha256',
            password.encode('utf-8'),
            salt,
            iterations,
            dklen=len(expected_hash),
        )
        return hashlib.compare_digest(dk, expected_hash)
    except (ValueError, KeyError, IndexError):
        return False
```