Coverage for agentos/marketplace/skills/encryption/encryption.py: 63%

35 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-07-04 16:43 +0800

1""" 

2encryption — 哈希摘要、Base64 编解码(纯 Python stdlib)。 

3 

4Category: security 

5""" 

6 

7 

8def run(action: str, text: str = "", file_path: str = "", algorithm: str = "sha256") -> str: 

9 """加密/哈希工具。action: hash/base64_encode/base64_decode/uuid。algorithm: sha256/md5/sha1/sha512。""" 

10 import hashlib, base64, os, uuid 

11 

12 def _input(): 

13 if file_path and os.path.isfile(file_path): 

14 with open(file_path,"rb") as f: 

15 return f.read() 

16 return text.encode("utf-8") 

17 

18 try: 

19 if action == "hash": 

20 data = _input() 

21 algo = algorithm.lower() 

22 if algo == "md5": h = hashlib.md5(data).hexdigest() 

23 elif algo == "sha1": h = hashlib.sha1(data).hexdigest() 

24 elif algo == "sha256": h = hashlib.sha256(data).hexdigest() 

25 elif algo == "sha512": h = hashlib.sha512(data).hexdigest() 

26 else: return f"[encryption] 不支持的算法: {algorithm}, 可用: md5/sha1/sha256/sha512" 

27 src = file_path if file_path else f"'{text[:30]}...'" if len(text)>30 else f"'{text}'" 

28 return f"{algo.upper()}({src}) = {h}" 

29 

30 if action == "base64_encode": 

31 data = _input() 

32 encoded = base64.b64encode(data).decode("utf-8") 

33 return encoded 

34 

35 if action == "base64_decode": 

36 data = text.encode("utf-8") if text else _input() 

37 try: 

38 decoded = base64.b64decode(data).decode("utf-8") 

39 except Exception: 

40 decoded = base64.b64decode(data).decode("latin-1") # might be binary 

41 return decoded 

42 

43 if action == "uuid": 

44 return f"UUID4: {uuid.uuid4()}\nUUID1: {uuid.uuid1()}" 

45 

46 return f"[encryption] 未知操作: {action}, 支持: hash/base64_encode/base64_decode/uuid" 

47 except Exception as e: 

48 return f"[encryption] 失败: {e}" 

49 

50 

51__all__ = ["run"]