← run

sec-password-hashing

0.000
0/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
# solution.py

import hashlib

def hash_password(password: str) -> str:
    """
    Hashes a password using SHA-256 with a salt.
    
    Args:
        password (str): The plaintext password to hash.
        
    Returns:
        str: The hashed password in the format 'salt$hash'.
    """
    # Generate a random salt
    salt = hashlib.sha256(password.encode('utf-8') + b'salt').hexdigest()
    
    # Hash the password with the salt
    hashed = hashlib.sha256((password + salt).encode('utf-8')).hexdigest()
    
    return f"{salt}${hashed}"

def verify_password(password: str, hashed: str) -> bool:
    """
    Verifies a password against a stored hash.
    
    Args:
        password (str): The plaintext password to verify.
        hashed (str): The stored hash string.
        
    Returns:
        bool: True if the password matches, False otherwise.
    """
    try:
        # Split the stored hash into salt and hash
        salt, stored_hash = hashed.split('$')
        
        # Recreate the hash using the stored salt
        computed_hash = hashlib.sha256((password + salt).encode('utf-8')).hexdigest()
        
        # Compare the computed hash with the stored hash
        return computed_hash == stored_hash
    except (ValueError, AttributeError):
        # Handle malformed hash strings
        return False
```