Passlib Argon2 Password Hashing

Hash passwords with Argon2id through passlib, storing algorithm parameters inline so upgrades rehash transparently on next login.

PythonSecurity Boundaries

Code

snippet
from passlib.context import CryptContext

context = CryptContext(
    schemes=['argon2'],
    argon2__type='ID',
    argon2__time_cost=3,
    argon2__memory_cost=65536,
    argon2__parallelism=4,
    deprecated='auto',
)


def hash_password(plain: str) -> str:
    return context.hash(plain)



def verify_password(plain: str, stored: str) -> str | None:
    ok, needs_rehash = context.verify_and_update(plain, stored)
    if not ok:
        return None
    if needs_rehash:
        # 参数升级或算法换代:下次登录时透明重哈希
        return context.hash(plain)
    return stored


record = hash_password('correct horse battery staple')
print('format:', record.split('$')[1])

print('wrong password:', verify_password('wrong', record) is None)
print('right password keeps hash:', verify_password('correct horse battery staple', record) == record)

# 模拟旧参数哈希:verify_and_update 报告需要升级
weaker = CryptContext(schemes=['argon2'], argon2__time_cost=1, argon2__memory_cost=8192)
legacy_record = weaker.hash('correct horse battery staple')
upgraded = verify_password('correct horse battery staple', legacy_record)
print('legacy upgraded:', upgraded != legacy_record)