WorkLog initial import
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
"""口令散列与登录令牌。只依赖标准库,避免额外依赖。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
ALGORITHM = "pbkdf2_sha256"
|
||||
ITERATIONS = 240_000
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""返回 pbkdf2_sha256$<迭代次数>$<盐hex>$<摘要hex>。"""
|
||||
salt = secrets.token_bytes(16)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS)
|
||||
return f"{ALGORITHM}${ITERATIONS}${salt.hex()}${digest.hex()}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
algorithm, iterations, salt_hex, digest_hex = stored.split("$")
|
||||
if algorithm != ALGORITHM:
|
||||
return False
|
||||
digest = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), int(iterations)
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(digest.hex(), digest_hex)
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
"""会话令牌,43 个字符的 URL 安全随机串。"""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_digest(token: str) -> str:
|
||||
"""数据库只保存高熵令牌的摘要,数据库副本不能直接充当登录凭据。"""
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
Reference in New Issue
Block a user