123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- import binascii
- import re
- from Crypto.Cipher import AES
- import base64
- class AESCBC:
- def __init__(self):
- self.key = 'A7uC*e^Et^l9Pvto' # 定义key值
- self.key = self.key.encode('utf-8')
- self.mode = AES.MODE_CBC
- self.bs = 16 # block size
- self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
- def encrypt(self, text):
- text = text.encode('utf-8')
- generator = AES.new(self.key, self.mode , b'0000000000000000') # 这里的key 和IV 一样 ,可以按照自己的值定义
- length = 16
- count = len(text)
- if count < length:
- add = (length - count)
- # \0 backspace
- # text = text + ('\0' * add)
- text = text + ('\0' * add).encode('utf-8')
- elif count > length:
- add = (length - (count % length))
- # text = text + ('\0' * add)
- text = text + ('\0' * add).encode('utf-8')
- crypt = generator.encrypt(text)
- crypted_str = base64.b64encode(crypt) #输出Base64
- # crypted_str = binascii.b2a_hex(crypt) # 输出Hex
- result = crypted_str.decode()
- return result
- def decrypt(self, text):
- generator = AES.new(self.key, self.mode,b'0000000000000000')
- # text += (len(text) % 4) * '='
- decrpyt_bytes = base64.b64decode(text) #输出Base64
- # decrpyt_bytes = binascii.a2b_hex(text) # 输出Hex
- meg = generator.decrypt(decrpyt_bytes)
- # 去除解码后的非法字符
- try:
- result = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', meg.decode())
- except Exception:
- result = '解码失败,请重试!'
- return result
- if __name__ == '__main__':
- aes = AESCBC()
- to_encrypt = '{"errcode":"-1", "errmsg" : "请输入产品编号", "traceId" : "174.132.15889293825631683"}'
- to_decrypt = '0VyJcW31Tj0d0eGXcGbpAeHTqcrKqYZIxTqUQGSiAZ8xDAm687ePSPwkeZgX4Eps379Ryh5UZFFjw8/Dh24RLRcl2cGUO7g+nQb1sP4eXH6e6PdiWlcXk8M3miq0dgHRvMBzdk/eJECHBefGR7ZbOQ=='
- print("\n加密前:{0}\n加密后:{1}\n".format(to_encrypt, aes.encrypt(to_encrypt)))
- print("解密前:{0}\n解密后:{1}".format(to_decrypt, aes.decrypt(to_decrypt)))
|