pbkdf2_hmac Derives And Verifies Passwords

Derive password verifiers with hashlib.pbkdf2_hmac under a per-record salt, then confirm candidates with secrets.compare_digest for constant-time comparison.

PythonAuth Jwt

Code

pythonsnippet
19 lines
import hashlib
import secrets

# 口令绝不存明文:pbkdf2_hmac 派生密钥,盐与迭代次数随记录一起保存
SALT = b"static-demo-salt"      # 生产环境应为每用户随机生成
ITERATIONS = 200_000

def derive(password: str) -> bytes:
    return hashlib.pbkdf2_hmac("sha256", password.encode(), SALT, ITERATIONS)

stored = derive("correct horse")
print("derived:", stored[:8].hex(), "...")

def verify(password: str, expected: bytes) -> bool:
    # compare_digest 恒时比较,避免逐字节提前返回的时序侧信道
    return secrets.compare_digest(derive(password), expected)

print("right password:", verify("correct horse", stored))
print("wrong password:", verify("Correct Horse", stored))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

derived: 6999adf1915f8ddc ...
right password: True
wrong password: False

How the snippet works

pbkdf2_hmac Derives And Verifies Passwords keeps everything in the functions derive and verify.

Applying it

Signature: def derive(password: str) -> bytes

Output lines are prefixed (derived:, right password:, wrong password:), making each step’s effect easy to spot.

Import derive from the file and call it — the rest of the code is implementation detail.

Statements that matter

def verify(password: str, expected: bytes) -> bool:
    # compare_digest 恒时比较,避免逐字节提前返回的时序侧信道
    return secrets.compare_digest(derive(password), expected)
def derive(password: str) -> bytes:
    return hashlib.pbkdf2_hmac("sha256", password.encode(), SALT, ITERATIONS)

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `hashlib`, `secrets`. The file defines `derive`, `verify` at load time.