Passlib Argon2 Password Hashing

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

PythonSecurity Boundaries

Code

pythonsnippet
38 lines
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)

What the code does

Count the functions hash_password and verify_password as the entire surface area of Passlib Argon2 Password Hashing.

The import line is the dependency contract: CryptContext comes from passlib and nothing else.

What to watch for

  • passlib must be installed first — the snippet imports it directly.

Applying it

Signature: def hash_password(plain: str) -> str

Running the file prints labeled results such as format:, wrong password:, right password keeps hash: — each operation’s effect is visible in the output.

hash_password is the public entry point; everything else in the file exists to support it.

Statements that matter

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
def hash_password(plain: str) -> str:
    return context.hash(plain)

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `passlib`. Add it to your project before running the snippet.