aescrypt.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2021/02/20
  3. # @Author : ricky
  4. # @File : aescrypt.py
  5. # @Software: vscode
  6. """
  7. AES加解密
  8. """
  9. from Crypto.Cipher import AES
  10. import base64
  11. AES_LENGTH = 16
  12. class AesCrypt():
  13. def __init__(self, key='ngf8t58XzWMYSMLK'):
  14. self.key = self.add_16(key)
  15. self.mode = AES.MODE_ECB
  16. self.aes = AES.new(self.key, self.mode)
  17. def add_16(self, par):
  18. if type(par) == str:
  19. par = par.encode()
  20. while len(par) % 16 != 0:
  21. par += b'\x00'
  22. return par
  23. def encrypt(self, text):
  24. """
  25. 加密
  26. 参数:
  27. text:明文
  28. """
  29. text = self.add_16(text)
  30. self.encrypt_text = self.aes.encrypt(text)
  31. return str(base64.encodebytes(self.encrypt_text),
  32. encoding='utf-8').strip('\0')
  33. def decrypt(self, text):
  34. """
  35. 解密
  36. 参数:
  37. text:密文
  38. """
  39. text = base64.decodebytes(text.encode(encoding='utf-8'))
  40. self.decrypt_text = self.aes.decrypt(text).strip(b"\x00")
  41. return str(self.decrypt_text, encoding='utf-8')