一、加密代码
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)
二·、报错相关
1、报错信息 cipher = AES.new(self.key, AES.MODE_CBC, iv) File "D:\Python37\Lib\Crypto\Cipher\AES.py", line 232, in new return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs) File "D:\Python37\Lib\Crypto\Cipher\__init__.py", line 79, in _create_cipher return modes[mode](factory, **kwargs) File "D:\Python37\Lib\Crypto\Cipher\_mode_cbc.py", line 274, in _create_cbc_cipher cipher_state = factory._create_base_cipher(kwargs) File "D:\Python37\Lib\Crypto\Cipher\AES.py", line 103, in _create_base_cipher result = start_operation(c_uint8_ptr(key), File "D:\Python37\Lib\Crypto\Util\_raw_api.py", line 144, in c_uint8_ptr raise TypeError("Object type %s cannot be passed to C code" % type(data)) TypeError: Object type <class 'str'> cannot be passed to C code 2、报错代码 cipher = AES.new(self.key, AES.MODE_CBC, iv)
三、报错原因
AES.new 方法的第一个参数,需要为 bytes/bytearray/memoryview 类型,报错代码中传递的是 字符串 类型,将其转为 bytes 类型即可
四、修改之后
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.encode(), 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)