一、加密代码
import base64 import zlib from Crypto.Cipher import AES from Crypto import Random BLOCK_SIZE = 16 def pad(s): return s + ((BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)).encode("utf-8") class AESCipher: def __init__(self, key): self.key = key def encrypt(self, raw): """ 加密 """ raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return iv + cipher.encrypt(raw) def encode(data, key) -> bytes: """ :param data: 序列化后的数据 :param key: 加密的 key :return: """ # 压缩 compress_data = zlib.compress(data) # 加密 aes = AESCipher(key) encrypt_data = aes.encrypt(compress_data) # 转成Base64编码 encode_data = base64.b64encode(encrypt_data) return encode_data if __name__ == '__main__': key = hashlib.md5(str(time.time()).encode('utf-8')).hexdigest() json_data = json.dumps({'data': 'test'}) encode_data = encode(json_data, key)