Files
EnuivTools/backend/admin/passwords.py
T

44 lines
1.0 KiB
Python

"""管理员口令。只保存慢哈希,不能从库里还原明文。"""
from __future__ import annotations
import hashlib
import hmac
import secrets
_N = 2**14
_R = 8
_P = 1
_PREFIX = "scrypt$"
_DEFAULT_PASSWORD = "242520"
_MIN_LENGTH = 6
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=_N, r=_R, p=_P)
return f"{_PREFIX}{salt.hex()}${digest.hex()}"
def verify_password(stored: str, password: str) -> bool:
if not stored.startswith(_PREFIX):
return False
try:
_, salt_hex, digest_hex = stored.split("$", 2)
calc = hashlib.scrypt(password.encode("utf-8"), salt=bytes.fromhex(salt_hex), n=_N, r=_R, p=_P)
except (ValueError, TypeError):
return False
return hmac.compare_digest(calc, bytes.fromhex(digest_hex))
def is_hashed(stored: str) -> bool:
return stored.startswith(_PREFIX)
def default_password() -> str:
return _DEFAULT_PASSWORD
def min_length() -> int:
return _MIN_LENGTH