import bcrypt class PasswordManager: @staticmethod def hash_password(password: str) -> str: """Hashes a plaintext password using bcrypt.""" # Generate a salt for the password. bcrypt will internally handle this. # gensalt() generates a new salt for each password. # The cost factor (rounds) can be adjusted; 12 is a common default. hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=12)) return hashed_password.decode('utf-8') @staticmethod def check_password(plaintext_password: str, hashed_password: str) -> bool: """Checks if a plaintext password matches a stored bcrypt hash.""" try: return bcrypt.checkpw(plaintext_password.encode('utf-8'), hashed_password.encode('utf-8')) except ValueError: # Handle cases where the hashed_password might be malformed or not a bcrypt hash return False # Example Usage: password = "MySecurePassword123!" # Hash the password secure_hash = PasswordManager.hash_password(password) print(f"Original password: {password}") print(f"Hashed password: {secure_hash}") # Verify the password is_correct = PasswordManager.check_password(password, secure_hash) print(f"Is '{password}' correct? {is_correct}") # Test with an incorrect password incorrect_password = "WrongPassword" is_incorrect = PasswordManager.check_password(incorrect_password, secure_hash) print(f"Is '{incorrect_password}' correct? {is_incorrect}") # Test with a malformed hash (should return False) is_malformed = PasswordManager.check_password(password, "not-a-valid-hash") print(f"Is '{password}' correct with malformed hash? {is_malformed}")