utils.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. from base64 import b64encode, b64decode
  2. from Crypto.Cipher import AES
  3. from Crypto.Util.Padding import pad, unpad
  4. from config.config import settings as app_settings
  5. def aes_encrypt(plain_text: str):
  6. cipher = AES.new(bytes.fromhex(app_settings.AES_ENCRYPTION_KEY), AES.MODE_CBC)
  7. ct_bytes = cipher.encrypt(pad(plain_text.encode(), AES.block_size))
  8. iv = b64encode(cipher.iv).decode("utf-8")
  9. ct = b64encode(ct_bytes).decode("utf-8")
  10. return f"{iv},{ct}"
  11. def aes_decrypt(encrypted_text: str):
  12. if encrypted_text is None or "," not in encrypted_text:
  13. return None
  14. iv, ct = encrypted_text.split(",", 1)
  15. iv = b64decode(iv)
  16. ct = b64decode(ct)
  17. cipher = AES.new(bytes.fromhex(app_settings.AES_ENCRYPTION_KEY), AES.MODE_CBC, iv)
  18. pt = unpad(cipher.decrypt(ct), AES.block_size)
  19. return pt.decode("utf-8")
  20. def revise_tool_names(tools: list):
  21. if not tools:
  22. return
  23. for tool in tools:
  24. if tool.get("type") != "retrieval":
  25. continue
  26. tool["type"] = "file_search"