您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

signature.py 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import base64
  2. import hashlib
  3. import hmac
  4. import os
  5. import time
  6. from configs import dify_config
  7. def sign_tool_file(tool_file_id: str, extension: str) -> str:
  8. """
  9. sign file to get a temporary url
  10. """
  11. base_url = dify_config.FILES_URL
  12. file_preview_url = f"{base_url}/files/tools/{tool_file_id}{extension}"
  13. timestamp = str(int(time.time()))
  14. nonce = os.urandom(16).hex()
  15. data_to_sign = f"file-preview|{tool_file_id}|{timestamp}|{nonce}"
  16. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  17. sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  18. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  19. return f"{file_preview_url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  20. def verify_tool_file_signature(file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  21. """
  22. verify signature
  23. """
  24. data_to_sign = f"file-preview|{file_id}|{timestamp}|{nonce}"
  25. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  26. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  27. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  28. # verify signature
  29. if sign != recalculated_encoded_sign:
  30. return False
  31. current_time = int(time.time())
  32. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT