| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- # coding=utf-8
- """
- 加密工具模块
- 用于平台API Key的SHA256哈希存储
- """
- import hashlib
- import secrets
- # API Key前缀常量
- API_KEY_PREFIX = "sk-aigc-"
- # API Key总长度(包含前缀)
- API_KEY_TOTAL_LENGTH = 48
- def hash_api_key(api_key: str) -> str:
- """
- 使用SHA256算法对API Key进行哈希
- 用于平台API Key的安全存储(单向哈希,不可逆)
- """
- if not api_key:
- return ""
- return hashlib.sha256(api_key.encode('utf-8')).hexdigest()
- def verify_api_key_hash(api_key: str, hashed: str) -> bool:
- """
- 验证API Key是否与哈希值匹配
- """
- if not api_key or not hashed:
- return False
- return hash_api_key(api_key) == hashed
- def generate_platform_api_key() -> tuple:
- """
- 生成平台API Key
- 生成以 "sk-aigc-" 为前缀、总长度48字符的安全随机密钥
- Returns:
- (full_key, display_prefix)
- """
- random_length = API_KEY_TOTAL_LENGTH - len(API_KEY_PREFIX)
- random_part = secrets.token_hex(random_length // 2)
- random_part = random_part[:random_length]
- full_key = f"{API_KEY_PREFIX}{random_part}"
- display_prefix = f"{API_KEY_PREFIX}{random_part[:4]}...{random_part[-4:]}"
- return full_key, display_prefix
|