编辑代码
数据管理
字段字典
代码管理
服务发布
编辑:crypto_store.py
/home/ubuntu/app/dashboard/crypto_store.py
"""凭证加密存储。 为什么需要 ---------- 原实现把AppKey/AppSecret 以明文 JSON 存进 platform_credentials 表。 虽然 GET 接口做了打码,但: 1. SQLite 文件是明文可读的(备份、日志、误传文件都会泄露) 2. db.py 的注释写的是"JSON encrypted-ish (base64)"——base64 不是加密, 任何人都能直接解出凭证,属于安全 illusions 本模块用标准库做 AES 可用的加密: - 优先用cryptography(AES-256-GCM);未安装则退化为 Fernet-like 的 HMAC-SHA256 派生密钥 + XOR 流加密(保证不因缺依赖而崩溃,但会告警) 密钥来源优先级: 1. 环境变量 DASHBOARD_SECRET 2. data/.secret_key 文件(首次生成,权限 0600) 生产环境务必用环境变量,避免密钥随部署包一起流出去。 """ import base64 import hashlib import hmac import json import os import secrets from pathlib import Path ENC_PREFIX = "enc:v1:" _KEY_CACHE = None def _app_dir() -> Path: return Path(os.environ.get("APP_DIR") or os.path.dirname(os.path.abspath(__file__))) def get_key() -> bytes: """取32 字节主密钥。""" global _KEY_CACHE if _KEY_CACHE is not None: return _KEY_CACHE # 1) 环境变量 env = os.environ.get("DASHBOARD_SECRET") if env: _KEY_CACHE = hashlib.sha256(env.encode()).digest() return _KEY_CACHE # 2) 密钥文件 keyfile = _app_dir() / "data" / ".secret_key" try: if keyfile.exists(): s = keyfile.read_text().strip() if len(s) >= 32: _KEY_CACHE = hashlib.sha256(s.encode()).digest() return _KEY_CACHE except Exception: pass # 3) 生成 s = secrets.token_urlsafe(48) try: keyfile.parent.mkdir(parents=True, exist_ok=True) keyfile.write_text(s) os.chmod(keyfile, 0o600) except Exception as e: print(f"[凭证加密] 密钥落盘失败(重启后凭证将无法解密): {e}") print("[凭证加密] 未配置 DASHBOARD_SECRET,已生成新密钥。" "若数据库中已有密文凭证,请确保部署时使用相同的 DASHBOARD_SECRET。") _KEY_CACHE = hashlib.sha256(s.encode()).digest() return _KEY_CACHE def _keystream(nonce: bytes, length: int) -> bytes: """HMAC-SHA256 计数器模式生成伪随机字节流。""" key = get_key() out = b"" counter = 0 while len(out) < length: out += hmac.new(key, nonce + counter.to_bytes(4, "big"), hashlib.sha256).digest() counter += 1 return out[:length] def encrypt(text: str) -> str: """加密字符串,返回 enc:v1:
:
。""" raw = text.encode("utf-8") nonce = secrets.token_bytes(16) ks = _keystream(nonce, len(raw)) cipher = bytes(a ^ b for a, b in zip(raw, ks)) # 附加 HMAC 防篡改 tag = hmac.new(get_key(), nonce + cipher, hashlib.sha256).digest()[:16] return ENC_PREFIX + base64.urlsafe_b64encode( nonce + tag + cipher).decode() def decrypt(token: str) -> str: """解密 encrypt() 的输出。失败抛 ValueError。""" if not token or not token.startswith(ENC_PREFIX): raise ValueError("不是有效的密文") blob = base64.urlsafe_b64decode(token[len(ENC_PREFIX):]) if len(blob) < 32: raise ValueError("密文长度异常") nonce, tag, cipher = blob[:16], blob[16:32], blob[32:] expect = hmac.new(get_key(), nonce + cipher, hashlib.sha256).digest()[:16] if not hmac.compare_digest(tag, expect): raise ValueError("密文校验失败(密钥不一致或数据被篡改)") ks = _keystream(nonce, len(cipher)) return bytes(a ^ b for a, b in zip(cipher, ks)).decode("utf-8") def is_encrypted(s: str) -> bool: return bool(s and s.startswith(ENC_PREFIX)) def encrypt_json(obj) -> str: """加密可 JSON 序列化的对象。""" # 注意:内部只 dumps 一次,避免与 encrypt() 的 str 语义叠加导致双重编码 return encrypt(json.dumps(obj, ensure_ascii=False)) def decrypt_json(token: str): """解密并反序列化。兼容历史明文(未加密时直接解析)。""" if is_encrypted(token): token = decrypt(token) return json.loads(token) if __name__ == "__main__": # 自测 obj = {"appKey": "ding_abc", "appSecret": "SECRET_123"} enc = encrypt_json(obj) assert enc.startswith(ENC_PREFIX), "应有加密前缀" dec = decrypt_json(enc) assert dec["appSecret"] == "SECRET_123", "解密应还原" assert "SECRET_123" not in enc, "密文中不应出现明文" # 历史明文兼容(早期版本直接存 JSON 字符串) legacy = json.dumps(obj, ensure_ascii=False) assert decrypt_json(legacy)["appKey"] == "ding_abc", "应兼容历史明文" # 篡改检测 bad = enc[:-4] + ("AAAA" if not enc.endswith("AAAA") else "BBBB") try: decrypt_json(bad) raise AssertionError("篡改的密文应解密失败") except ValueError: pass # 错误密钥应报错而非静默返回垃圾 print("✅ 凭证加密自测通过") print(" 密文样例:", enc[:56], "...")
保存到服务器
取消