nex_buddy/server/app/core/security.py

57 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""口令哈希与 token 生成。
设计要点(01-总体设计.md 第 7 节):口令用 bcrypt 存哈希;token 只存哈希,
即使 Redis 被读也无法反推出可用的凭证。
"""
from __future__ import annotations
import hashlib
import secrets
import bcrypt
# bcrypt 只取前 72 字节,超长口令先截断,避免不同口令哈希相同
_MAX = 72
def hash_password(raw: str) -> str:
return bcrypt.hashpw(raw.encode("utf-8")[:_MAX], bcrypt.gensalt(rounds=12)).decode()
def verify_password(raw: str, stored: str) -> bool:
try:
return bcrypt.checkpw(raw.encode("utf-8")[:_MAX], stored.encode())
except ValueError:
return False
def new_token() -> str:
"""会话/设备 token:32 字节随机,URL 安全。"""
return secrets.token_urlsafe(32)
def token_hash(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def new_pair_code() -> str:
"""6 位数字配对码,避开前导 0 便于屏显与手输。"""
return str(secrets.randbelow(900000) + 100000)
def normalize_pair_code(code: str) -> str:
return "".join(ch for ch in (code or "") if ch.isdigit())[:6]
# 扫码登录票据:大写字母 + 数字,去掉 0/O、1/I 这类扫错眼睛的字符
_LOGIN_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
def new_web_login_code(n: int = 10) -> str:
return "".join(secrets.choice(_LOGIN_ALPHABET) for _ in range(n))
def normalize_web_login_code(code: str) -> str:
return "".join(ch for ch in (code or "").upper() if ch in _LOGIN_ALPHABET)[:16]