fix: 管理员口令改为哈希并限制连续失败

This commit is contained in:
2026-11-16 02:35:15 +08:00
parent 77f80ad0e1
commit 0fbc3146d8
11 changed files with 209 additions and 26 deletions
+38
View File
@@ -0,0 +1,38 @@
"""管理员口令。只保存慢哈希,不能从库里还原明文。"""
from __future__ import annotations
import hashlib
import hmac
import secrets
_N = 2**14
_R = 8
_P = 1
_PREFIX = "scrypt$"
_LEGACY_PASSWORD = "242520"
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 legacy_password() -> str:
return _LEGACY_PASSWORD