rsa_crypto.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from abc import ABC, abstractmethod
  2. from Cryptodome.PublicKey import RSA
  3. from Cryptodome.Cipher import PKCS1_v1_5
  4. import base64
  5. import rsa
  6. # 定义抽象基类
  7. class RSACrypto(ABC):
  8. @abstractmethod
  9. def encrypt(self, password: str) -> str:
  10. pass
  11. @abstractmethod
  12. def decrypt(self, encrypted_password: str) -> str:
  13. pass
  14. # 实现 RagflowCrypto 类
  15. class RagflowCrypto(RSACrypto):
  16. def __init__(self, public_key: str, private_key: str):
  17. self.public_key = public_key
  18. self.private_key = private_key
  19. def encrypt(self, password: str) -> str:
  20. rsa_key = RSA.importKey(self.public_key)
  21. cipher = PKCS1_v1_5.new(rsa_key)
  22. encrypted_password = cipher.encrypt(base64.b64encode(password.encode('utf-8')))
  23. return base64.b64encode(encrypted_password).decode('utf-8')
  24. def decrypt(self, encrypted_password: str) -> str:
  25. rsa_key = RSA.importKey(self.private_key)
  26. cipher = PKCS1_v1_5.new(rsa_key)
  27. encrypted_password_bytes = base64.b64decode(encrypted_password)
  28. decoded_password = cipher.decrypt(encrypted_password_bytes, "Fail to decrypt password!")
  29. return base64.b64decode(decoded_password).decode('utf-8')
  30. # 实现 BishengCrypto 类
  31. # class BishengCrypto(RSACrypto):
  32. #
  33. # def __init__(self, public_key, private_key: str):
  34. # self.public_key = public_key
  35. # self.private_key = private_key
  36. #
  37. # def encrypt(self, password: str) -> str:
  38. # rsa_key = RSA.importKey(self.public_key)
  39. # cipher = PKCS1_v1_5.new(rsa_key)
  40. # encrypted_password = cipher.encrypt(password.encode('utf-8'))
  41. # return base64.b64encode(encrypted_password).decode('utf-8')
  42. #
  43. # def decrypt(self, encrypted_password: str) -> str:
  44. # rsa_key = RSA.importKey(self.private_key)
  45. # cipher = PKCS1_v1_5.new(rsa_key)
  46. # encrypted_password_bytes = base64.b64decode(encrypted_password)
  47. # decoded_password = cipher.decrypt(encrypted_password_bytes, "Fail to decrypt password!")
  48. # return decoded_password.decode('utf-8')
  49. class BishengCrypto:
  50. def __init__(self, public_key: str, private_key: str):
  51. self.public_key = rsa.PublicKey.load_pkcs1(public_key.encode('utf-8'))
  52. def encrypt(self, password: str) -> str:
  53. encrypted_password = rsa.encrypt(password.encode('utf-8'), self.public_key)
  54. return base64.b64encode(encrypted_password).decode('utf-8')
  55. @classmethod
  56. def decrypt(cls, password: str, private_key: str) -> str:
  57. private_key = rsa.PrivateKey.load_pkcs1(private_key.encode('utf-8'))
  58. encrypted_password_bytes = base64.b64decode(password)
  59. return rsa.decrypt(encrypted_password_bytes, private_key).decode('utf-8')