ase_utils.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from Crypto.Cipher import AES
  4. import base64
  5. BLOCK_SIZE = 16 # Bytes
  6. pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
  7. chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
  8. unpad = lambda s: s[:-ord(s[len(s) - 1:])]
  9. def aesEncrypt(key, data):
  10. '''
  11. AES的ECB模式加密方法
  12. :param key: 密钥
  13. :param data:被加密字符串(明文)
  14. :return:密文
  15. '''
  16. key = key.encode('utf8')
  17. # 字符串补位
  18. data = pad(data)
  19. cipher = AES.new(key, AES.MODE_ECB)
  20. # 加密后得到的是bytes类型的数据,使用Base64进行编码,返回byte字符串
  21. result = cipher.encrypt(data.encode())
  22. encodestrs = base64.b64encode(result)
  23. enctext = encodestrs.decode('utf8')
  24. # print(enctext)
  25. return enctext
  26. def aesDecrypt(key, data):
  27. '''
  28. :param key: 密钥
  29. :param data: 加密后的数据(密文)
  30. :return:明文
  31. '''
  32. key = key.encode('utf8')
  33. data = base64.b64decode(data)
  34. cipher = AES.new(key, AES.MODE_ECB)
  35. # 去补位
  36. text_decrypted = unpad(cipher.decrypt(data))
  37. text_decrypted = text_decrypted.decode('utf8')
  38. # print(text_decrypted)
  39. return text_decrypted