crypto_utils.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # coding=utf-8
  2. """
  3. 加密工具模块
  4. 用于平台API Key的SHA256哈希存储
  5. """
  6. import hashlib
  7. import secrets
  8. # API Key前缀常量
  9. API_KEY_PREFIX = "sk-aigc-"
  10. # API Key总长度(包含前缀)
  11. API_KEY_TOTAL_LENGTH = 48
  12. def hash_api_key(api_key: str) -> str:
  13. """
  14. 使用SHA256算法对API Key进行哈希
  15. 用于平台API Key的安全存储(单向哈希,不可逆)
  16. """
  17. if not api_key:
  18. return ""
  19. return hashlib.sha256(api_key.encode('utf-8')).hexdigest()
  20. def verify_api_key_hash(api_key: str, hashed: str) -> bool:
  21. """
  22. 验证API Key是否与哈希值匹配
  23. """
  24. if not api_key or not hashed:
  25. return False
  26. return hash_api_key(api_key) == hashed
  27. def generate_platform_api_key() -> tuple:
  28. """
  29. 生成平台API Key
  30. 生成以 "sk-aigc-" 为前缀、总长度48字符的安全随机密钥
  31. Returns:
  32. (full_key, display_prefix)
  33. """
  34. random_length = API_KEY_TOTAL_LENGTH - len(API_KEY_PREFIX)
  35. random_part = secrets.token_hex(random_length // 2)
  36. random_part = random_part[:random_length]
  37. full_key = f"{API_KEY_PREFIX}{random_part}"
  38. display_prefix = f"{API_KEY_PREFIX}{random_part[:4]}...{random_part[-4:]}"
  39. return full_key, display_prefix