""" Password security utilities using bcrypt for secure password hashing. This module provides secure password hashing and verification functions using the bcrypt algorithm with automatic salt generation. """ import bcrypt from typing import Union def hash_password(password: str) -> str: """ Hash a password using bcrypt with automatic salt generation. Args: password: The plain text password to hash Returns: The hashed password as a string Raises: ValueError: If password is empty or None RuntimeError: If bcrypt hashing fails """ if not password: raise ValueError("Password cannot be empty or None") try: # Encode password to bytes and generate salt password_bytes = password.encode('utf-8') salt = bcrypt.gensalt() # Hash the password hashed = bcrypt.hashpw(password_bytes, salt) # Return as string return hashed.decode('utf-8') except Exception as e: raise RuntimeError(f"Failed to hash password: {str(e)}") def verify_password(password: str, hashed_password: str) -> bool: """ Verify a password against its hash. Args: password: The plain text password to verify hashed_password: The hashed password to verify against Returns: True if password matches the hash, False otherwise Raises: ValueError: If password or hashed_password is empty or None RuntimeError: If password verification fails due to malformed hash """ if not password or not hashed_password: raise ValueError("Password and hashed_password cannot be empty or None") try: # Encode inputs to bytes password_bytes = password.encode('utf-8') hashed_bytes = hashed_password.encode('utf-8') # Verify password return bcrypt.checkpw(password_bytes, hashed_bytes) except ValueError as e: # bcrypt raises ValueError for malformed hashes raise RuntimeError(f"Invalid hash format: {str(e)}") except Exception as e: raise RuntimeError(f"Failed to verify password: {str(e)}")