prp.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # @author: rui.xu
  4. # @update: jt.huang
  5. # 这里使用pycrypto‎demo库
  6. #https://www.cnblogs.com/huangjianting/p/8666446.html
  7. #https://blog.csdn.net/wang_hugh/article/details/83994750
  8. #https://www.cnblogs.com/sammy1989/p/9663517.html
  9. #https://www.cnblogs.com/chen0307/p/11345601.html
  10. ##注:python3 安装 Crypto 是 pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple pycryptodome<br><br>
  11. from Crypto.Cipher import AES
  12. from binascii import b2a_hex, a2b_hex
  13. import base64
  14. import re
  15. class PrpCrypt(object):
  16. def __init__(self, key):
  17. self.key = key.encode('utf-8')
  18. self.mode = AES.MODE_CBC
  19. # 加密函数,如果text不足16位就用空格补足为16位,
  20. # 如果大于16当时不是16的倍数,那就补足为16的倍数。
  21. def encrypt(self, text):
  22. text = text.encode('utf-8')
  23. cryptor = AES.new(self.key, self.mode, b'0000000000000000')
  24. # 这里密钥key 长度必须为16(AES-128),
  25. # 24(AES-192),或者32 (AES-256)Bytes 长度
  26. # 目前AES-128 足够目前使用
  27. length = 16
  28. count = len(text)
  29. if count < length:
  30. add = (length - count)
  31. # \0 backspace
  32. # text = text + ('\0' * add)
  33. text = text + ('\0' * add).encode('utf-8')
  34. elif count > length:
  35. add = (length - (count % length))
  36. # text = text + ('\0' * add)
  37. text = text + ('\0' * add).encode('utf-8')
  38. self.ciphertext = cryptor.encrypt(text)
  39. # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
  40. # 所以这里统一把加密后的字符串转化为16进制字符串
  41. # return b2a_hex(self.ciphertext)
  42. return base64.b64encode(self.ciphertext);
  43. # 解密后,去掉补足的空格用strip() 去掉
  44. def decrypt(self, text):
  45. cryptor = AES.new(self.key, self.mode, b'0000000000000000')
  46. decryptByts = base64.b64decode(text)
  47. plain_text = cryptor.decrypt(decryptByts)
  48. result = re.compile('\n\reS80\x1c\x07\'\x018lBf~\x7f').sub('{"errcode":', plain_text.decode())
  49. result = result.replace("\n","")
  50. result = result.replace("\t", "")
  51. #
  52. #
  53. return result.replace("","").replace("","")
  54. if __name__ == '__main__':
  55. pc = PrpCrypt('CJGD@0qv0D*MMP*7') # 初始化密钥
  56. # d = pc.decrypt("0VyJcW31Tj0d0eGXcGbpAeHTqcrKqYZIxTqUQGSiAZ8xDAm687ePSPwkeZgX4Eps379Ryh5UZFFjw8/Dh24RLRcl2cGUO7g+nQb1sP4eXH6e6PdiWlcXk8M3miq0dgHRvMBzdk/eJECHBefGR7ZbOQ==") # 解密
  57. #
  58. e = pc.encrypt('{"errcode1":"-1", "errmsg" : "请输入产品编号", "traceId" : "174.132.15889293825631683"}') # 加密
  59. print("加密:", e)
  60. d = pc.decrypt(e);
  61. print("解密:", d)
  62. # d = pc.decrypt(d)
  63. # print("解密:", d)