prpcrypt.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import binascii
  4. import re
  5. from Crypto.Cipher import AES
  6. import base64
  7. class AESCBC:
  8. def __init__(self):
  9. self.key = 'A7uC*e^Et^l9Pvto' # 定义key值
  10. self.key = self.key.encode('utf-8')
  11. self.mode = AES.MODE_CBC
  12. self.bs = 16 # block size
  13. self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
  14. def encrypt(self, text):
  15. text = text.encode('utf-8')
  16. generator = AES.new(self.key, self.mode , b'0000000000000000') # 这里的key 和IV 一样 ,可以按照自己的值定义
  17. length = 16
  18. count = len(text)
  19. if count < length:
  20. add = (length - count)
  21. # \0 backspace
  22. # text = text + ('\0' * add)
  23. text = text + ('\0' * add).encode('utf-8')
  24. elif count > length:
  25. add = (length - (count % length))
  26. # text = text + ('\0' * add)
  27. text = text + ('\0' * add).encode('utf-8')
  28. crypt = generator.encrypt(text)
  29. crypted_str = base64.b64encode(crypt) #输出Base64
  30. # crypted_str = binascii.b2a_hex(crypt) # 输出Hex
  31. result = crypted_str.decode()
  32. return result
  33. def decrypt(self, text):
  34. generator = AES.new(self.key, self.mode,b'0000000000000000')
  35. # text += (len(text) % 4) * '='
  36. decrpyt_bytes = base64.b64decode(text) #输出Base64
  37. # decrpyt_bytes = binascii.a2b_hex(text) # 输出Hex
  38. meg = generator.decrypt(decrpyt_bytes)
  39. # 去除解码后的非法字符
  40. try:
  41. result = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', meg.decode())
  42. except Exception:
  43. result = '解码失败,请重试!'
  44. return result
  45. if __name__ == '__main__':
  46. aes = AESCBC()
  47. to_encrypt = '{"errcode":"-1", "errmsg" : "请输入产品编号", "traceId" : "174.132.15889293825631683"}'
  48. to_decrypt = '0VyJcW31Tj0d0eGXcGbpAeHTqcrKqYZIxTqUQGSiAZ8xDAm687ePSPwkeZgX4Eps379Ryh5UZFFjw8/Dh24RLRcl2cGUO7g+nQb1sP4eXH6e6PdiWlcXk8M3miq0dgHRvMBzdk/eJECHBefGR7ZbOQ=='
  49. print("\n加密前:{0}\n加密后:{1}\n".format(to_encrypt, aes.encrypt(to_encrypt)))
  50. print("解密前:{0}\n解密后:{1}".format(to_decrypt, aes.decrypt(to_decrypt)))