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.
Code
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: FalseHow 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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.