Files
password-security-python/tests/test_hashing.py
2025-11-13 23:56:05 +00:00

40 lines
1.4 KiB
Python

import re
from salt import hash_password, verify_password
def test_hash_password_round_trip() -> None:
salt, hashed = hash_password("correct horse battery staple")
assert verify_password("correct horse battery staple", salt, hashed)
assert not verify_password("wrong", salt, hashed)
def test_hash_password_returns_base64() -> None:
salt, hashed = hash_password("secret")
base64_pattern = re.compile(r"^[A-Za-z0-9+/]+={0,2}$")
assert base64_pattern.fullmatch(salt)
assert base64_pattern.fullmatch(hashed)
def test_verify_password_handles_invalid_base64() -> None:
assert verify_password("secret", "**invalid**", "???") is False
def test_hash_password_with_algorithm_parameter():
"""Verify hash_password accepts algorithm parameter."""
salt, hashed = hash_password("test", algorithm="pbkdf2")
assert verify_password("test", salt, hashed, algorithm="pbkdf2")
def test_backward_compatibility_with_old_pbkdf2_hashes():
"""Verify existing PBKDF2 hashes still work without algorithm parameter."""
# Simulate old hash created before algorithm parameter existed
salt, hashed = hash_password("legacy-password")
# Verify using old API (no algorithm parameter)
assert verify_password("legacy-password", salt, hashed)
assert not verify_password("wrong", salt, hashed)
# Verify using new API with explicit pbkdf2
assert verify_password("legacy-password", salt, hashed, algorithm="pbkdf2")