Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

删除默认的加解密工具,对token和api进行加解密

openJiuwen-bot67723e3191ef
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index d52932c60e..9e5a57664a 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -280,11 +280,12 @@ def _register_web_handlers(
for param_key, env_key in _CONFIG_SET_ENV_MAP.items()
}
payload["app_version"] = __version__
- if "api_key" in payload:
- payload['api_key'] = get_crypto_provider().decrypt(payload['api_key'])
# 合并 config.yaml 中的配置项
try:
raw = get_config_raw()
+ for key, val in payload.items():
+ if ("api_key" in key or "token" in key) and get_crypto_provider():
+ payload[key] = get_crypto_provider().decrypt(val)
ctx_cfg = (raw.get("react") or {}).get("context_engine_config") or {}
payload["context_engine_enabled"] = "true" if ctx_cfg.get("enabled", False) else "false"
perm_cfg = raw.get("permissions") or {}
@@ -326,12 +327,13 @@ def _register_web_handlers(
logger.warning("[config.set] 写回 .env 失败: %s", e)
async def _config_set(ws, req_id, params, session_id):
- if "api_key" in params:
- params["api_key"] = get_crypto_provider().encrypt(params["api_key"])
"""根据前端消息内容更新配置(支持 .env 与 config.yaml 中的键),并写回对应文件。"""
if not isinstance(params, dict):
await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
return
+ for key, val in params.items():
+ if ("api_key" in key or "token" in key) and get_crypto_provider():
+ params[key] = get_crypto_provider().encrypt(val)
env_updates: dict[str, str] = {}
yaml_updated: list[str] = []
available_model_providers = [provider.value for provider in ProviderType]
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index fd55ca0e5e..fcb9db8549 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -44,7 +44,8 @@ def resolve_env_vars(value: Any) -> Any:
var_name = match.group(1)
default = match.group(2)
current = os.getenv(var_name)
- if var_name == "API_KEY":
+ is_need_decrypt = ("API_KEY" in var_name or "TOKEN" in var_name) and current
+ if get_crypto_provider() and is_need_decrypt:
current = get_crypto_provider().decrypt(current)
# Bash: ${VAR:-default} uses default when VAR is unset OR empty.
# ${VAR} (no :-) keeps getenv behavior; unset -> "".
diff --git a/jiuwenclaw/security/base_crypto.py b/jiuwenclaw/security/base_crypto.py
index 1d1b7da116..1f3b94a217 100644
--- a/jiuwenclaw/security/base_crypto.py
+++ b/jiuwenclaw/security/base_crypto.py
@@ -1,132 +1,4 @@
-import secrets
-from abc import (
- ABC,
- abstractmethod,
-)
-from typing import Protocol, runtime_checkable
-from Crypto.Cipher import AES
-from jiuwenclaw.utils import logger
-
-
-class BaseCrypto(ABC):
- _instance = None # 单例缓存
- _other_classes = [] # 按定义顺序存储子类
- _default_subclass = None # 标记哪个是 DefaultCrypto
-
- def __init_subclass__(cls, **kwargs):
- # 如果子类名是 'DefaultCrypto',则标记为默认子类
- if cls.__name__ == "DefaultCrypto":
- BaseCrypto._default_subclass = cls
- else:
- BaseCrypto._other_classes.append(cls)
- logger.info(f"Registered crypto class: {cls.__name__}")
-
- @staticmethod
- def get_instance():
- """获取全局唯一实例,优先使用非 DefaultCrypto 的子类"""
- if BaseCrypto._instance is None:
- # 寻找第一个非 DefaultCrypto 的子类
- selected_cls = BaseCrypto._default_subclass
- if BaseCrypto._other_classes:
- selected_cls = BaseCrypto._other_classes[0]
-
- logger.info(f"创建实例,使用的子类: {selected_cls.__name__}")
- BaseCrypto._instance = selected_cls()
- return BaseCrypto._instance
-
- @abstractmethod
- def encrypt(self, plaintext: str, **kwargs) -> str:
- pass
-
- @abstractmethod
- def decrypt(self, ciphertext: str, **kwargs) -> str:
- pass
-
-
-NONCE_LENGTH = 12
-BIT_LENGTH = 8
-AES_KEY_LENGTH = 32
-TAG_LENGTH = 16
-NONCE_HEX_LENGTH = NONCE_LENGTH * 2 # hex_length = bytes_length * 2
-TAG_HEX_LENGTH = TAG_LENGTH * 2 # hex_length = bytes_length * 2
-DEFAULT_KEY = b'00000000000000000000000000000000'
-
-
-def _encrypt(key: bytes, plaintext: str):
- if len(key) != AES_KEY_LENGTH:
- raise ValueError(f'Wrong key length: {len(key)}, expected {AES_KEY_LENGTH}')
- random_instance = secrets.SystemRandom()
- nonce = bytes([random_instance.getrandbits(BIT_LENGTH) for _ in range(0, NONCE_LENGTH)])
- cipher = AES.new(key=key, mode=AES.MODE_GCM, nonce=nonce, mac_len=TAG_LENGTH)
- cipher_text, tag = cipher.encrypt_and_digest(plaintext.encode(encoding="utf-8"))
- return [cipher_text.hex(), nonce.hex(), tag.hex()]
-
-
-def _decrypt(key: bytes, ciphertext: str, nonce: str, tag: str):
- ciphertext_bytes = bytes.fromhex(ciphertext)
- nonce_bytes = bytes.fromhex(nonce)
- tag_bytes = bytes.fromhex(tag)
- if len(key) != AES_KEY_LENGTH:
- raise ValueError(f'Wrong key length: {len(key)}, expected {AES_KEY_LENGTH}')
-
- if len(nonce_bytes) != NONCE_LENGTH:
- raise ValueError(f"Wrong nonce length: {len(nonce_bytes)}")
-
- if len(tag_bytes) != TAG_LENGTH:
- raise ValueError(f"Wrong tag length: {len(tag_bytes)}, expected {TAG_LENGTH}")
-
- cipher = AES.new(key=key, mode=AES.MODE_GCM, nonce=nonce_bytes)
- plaintext_bytes = cipher.decrypt_and_verify(ciphertext=ciphertext_bytes, received_mac_tag=tag_bytes)
- return plaintext_bytes.decode(encoding="utf-8")
-
-
-def encrypt(plaintext: str, **kwargs) -> str:
- key = kwargs.get('key')
- if key is not None and not isinstance(key, bytes):
- key = str(key).encode('utf-8')
- if not key:
- key = DEFAULT_KEY
- if not plaintext:
- return plaintext
- try:
- encrypt_memory, nonce, tag = _encrypt(key=key, plaintext=plaintext)
- return f"{nonce}{tag}{encrypt_memory}"
- except Exception as e:
- logger.warning("Encrypt error occurred: %s", str(e))
- return plaintext
-
-
-def decrypt(ciphertext: str, **kwargs) -> str:
- key = kwargs.get('key')
- if key is not None and not isinstance(key, bytes):
- key = str(key).encode('utf-8')
- if not key:
- key = DEFAULT_KEY
- if not ciphertext:
- return ciphertext
- nonce_and_tag_len = NONCE_HEX_LENGTH + TAG_HEX_LENGTH
- if len(ciphertext) < nonce_and_tag_len:
- logger.warning(
- "Decryption error occurred: invalid ciphertext, ciphertext_len = %s", len(ciphertext)
- )
- return ciphertext
-
- nonce = ciphertext[0:NONCE_HEX_LENGTH]
- tag = ciphertext[NONCE_HEX_LENGTH:nonce_and_tag_len]
- encrypt_memory = ciphertext[nonce_and_tag_len:]
- try:
- return _decrypt(key=key, ciphertext=encrypt_memory, nonce=nonce, tag=tag)
- except Exception as e:
- logger.warning("Decrypt error occurred: %s", str(e))
- return ciphertext
-
-
-class DefaultCrypto(BaseCrypto):
- def encrypt(self, plaintext: str, **kwargs) -> str:
- return encrypt(plaintext, **kwargs)
-
- def decrypt(self, ciphertext: str, **kwargs) -> str:
- return decrypt(ciphertext, **kwargs)
+from typing import Protocol, runtime_checkable, Optional
@runtime_checkable
@@ -137,7 +9,8 @@ class CryptoProvider(Protocol):
def decrypt(self, ciphertext: str, **kwargs) -> str:
pass
-_default_provider: CryptoProvider = DefaultCrypto()
+
+_default_provider: CryptoProvider = None
def set_crypto_provider(provider: CryptoProvider) -> None:
@@ -145,5 +18,5 @@ def set_crypto_provider(provider: CryptoProvider) -> None:
_default_provider = provider
-def get_crypto_provider() -> CryptoProvider:
+def get_crypto_provider() -> Optional[CryptoProvider]:
return _default_provider
\ No newline at end of file