nex_animation/backend/app/services/secrets.py

99 lines
3.5 KiB
Python
Raw Normal View History

2026-11-01 08:18:07 +00:00
"""模型密钥的本地加密存储。
模型管理中心会登记供应商 API Key。这类凭据不能明文落库、更不能原样回传前端,
因此这里做两件事:
1. **加密**:用 HMAC-SHA256 派生的密钥流做 CTR 式异或,再用 HMAC 标签做完整性校验
(encrypt-then-MAC)。只依赖标准库,不引入额外依赖,部署环境更干净。
2. **脱敏**:接口层只回传 ``sk-****abcd`` 这类掩码,前端据此提示「已配置」。
主密钥优先取环境变量 ``MODEL_SECRET_KEY``(任意字符串),
否则在数据库 ``model_secret_keys`` 表里生成一条随机主密钥——
这样备份数据库就能带走密文,换机器不会出现「密文变乱码」的坑。
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import os
import secrets
from sqlalchemy.orm import Session
from app.models import ModelSecretKey
_ENV_KEY = "MODEL_SECRET_KEY"
_MASK_TAIL = 4
_MASK_HEAD = 3
# ---------------------------------------------------------------- 主密钥
def _master_key(db: Session) -> bytes:
env = (os.environ.get(_ENV_KEY) or "").strip()
if env:
return hashlib.sha256(env.encode("utf-8")).digest()
row = db.query(ModelSecretKey).order_by(ModelSecretKey.id).first()
if row and row.key_value:
return base64.urlsafe_b64decode(row.key_value.encode("ascii"))
raw = secrets.token_bytes(32)
db.add(ModelSecretKey(key_value=base64.urlsafe_b64encode(raw).decode("ascii")))
db.commit()
return raw
# ---------------------------------------------------------------- 加解密
def _keystream(key: bytes, nonce: bytes, length: int) -> bytes:
out = bytearray()
counter = 0
while len(out) < length:
block = hmac.new(key, nonce + counter.to_bytes(4, "big"), hashlib.sha256).digest()
out.extend(block)
counter += 1
return bytes(out[:length])
def encrypt_value(db: Session, plaintext: str) -> str:
"""加密明文;返回可直接落库的 base64 字符串。"""
if not plaintext:
return ""
key = _master_key(db)
nonce = secrets.token_bytes(12)
data = plaintext.encode("utf-8")
cipher = bytes(a ^ b for a, b in zip(data, _keystream(key, nonce, len(data))))
tag = hmac.new(key, nonce + cipher, hashlib.sha256).digest()
return base64.urlsafe_b64encode(nonce + tag + cipher).decode("ascii")
def decrypt_value(db: Session, payload: str) -> str:
"""解密;失败(主密钥更换、数据损坏)时返回空串,绝不抛异常打断业务流程。"""
if not payload:
return ""
try:
key = _master_key(db)
raw = base64.urlsafe_b64decode(payload.encode("ascii"))
nonce, tag, cipher = raw[:12], raw[12:44], raw[44:]
expect = hmac.new(key, nonce + cipher, hashlib.sha256).digest()
if not hmac.compare_digest(tag, expect):
return ""
return bytes(a ^ b for a, b in zip(cipher, _keystream(key, nonce, len(cipher)))).decode("utf-8")
except Exception:
return ""
# ---------------------------------------------------------------- 脱敏
def mask_value(plaintext: str | None) -> str:
"""把 API Key 变成掩码:``sk-****abcd``。太短的串直接打码。"""
if not plaintext:
return ""
text = str(plaintext)
if len(text) <= _MASK_HEAD + _MASK_TAIL:
return "*" * len(text)
head = text[:_MASK_HEAD]
tail = text[-_MASK_TAIL:]
return f"{head}{'*' * 4}{tail}"
def has_value(plaintext: str | None) -> bool:
return bool(plaintext)