← 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


To solve this problem, we need to securely store and verify user passwords using strong cryptographic hashing. The solution involves two functions: `hash_password` for securely hashing passwords and `verify_password` for checking if a given password matches its hashed version.

### Approach
The approach leverages the bcrypt hashing library, which is known for its security features, including the use of a salt to protect against dictionary attacks. Here's a detailed breakdown of the approach:

1. **Hashing Passwords**:
   - Use bcrypt's `gensalt()` function to generate a salt, which is a random value used to ensure that identical passwords produce different hash values.
   - Encode the password string into bytes using UTF-8 encoding.
   - Use bcrypt's `hashpw()` function to hash the password with the generated salt. This function returns the combined salt and hash as a bytes object.
   - Convert the resulting bytes object to a string for storage.

2. **Verifying Passwords**:
   - Encode the input password string into bytes.
   - Use bcrypt's `checkpw()` function to compare the provided password with the stored hash. This function handles the salt extraction and comparison internally.
   - Return a boolean indicating whether the password matches the hash.

### Solution Code
```python
import bcrypt

def hash_password(password: str) -> str:
    password_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(password_bytes, salt)
    return hashed.decode('utf-8')

def verify_password(password: str, hashed: str) -> bool:
    password_bytes = password.encode('utf-8')
    hashed_bytes = hashed.encode('utf-8')
    return bcrypt.checkpw(password_bytes, hashed_bytes)
```

### Explanation
- **hash_password**:
  - Converts the input password string to bytes.
  - Generates a salt using `bcrypt.gensalt()`.
  - Hashes the password with the salt using `bcrypt.hashpw()`.
  - Returns the hashed value as a string for storage.

- **verify_password**:
  - Converts the input password and hashed string to bytes.
  - Uses `bcrypt.checkpw()` to verify if the password matches the stored hash.
  - Returns `True` if the password is correct, otherwise `False`.

This approach ensures that passwords are securely hashed and verified, providing robust protection against common security threats.