Python实现AES中ECB模式pkcs5padding填充加密/解密(需要加密文档中可以有中文)
一、本文主要解决的问题
本文主要是讲解AES加密算法中的ECB模式的加密解密的Python3.7实现,以及遇到的问题。具体AES加密算法的原理这里不做过多介绍,想了解的更多关于AES加密可以参考文末的AES加密算法的详细介绍与实现。
二、完整版代码
废话不多说直接上代码
import base64
import json
import requests
from Crypto.Cipher import AES
class EncryptDate:
def __init__(self, key):
self.key = key.encode("utf-8") # 初始化密钥
self.length = AES.block_size # 初始化数据块大小
self.aes = AES.new(self.key, AES.MODE_ECB) # 初始化AES,ECB模式的实例
# 截断函数,去除填充的字符
self.unpad = lambda date: date[0:-ord(date[-1])]
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
entext = text + (chr(add) * add)
return entext
def encrypt(self, encrData): # 加密函数
res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
msg = str(base64.b64encode(res), encoding="utf8")
return msg
def decrypt(self, decrData): # 解密函数
res = base64.decodebytes(decrData.encode("utf8"))
msg = self.aes.decrypt(res).decode("utf8")
return self.unpad(msg)
eg = EncryptDate("xxxxaaaabbbbcccc") # 这里密钥的长度必须是16的倍数
data = {"hotelCode": "330122892X", "realName": "张四五", "sex": "1"}
res = eg.encrypt(str(data))
print(res)
print(eg.decrypt(res))
结果:
三、遇到的问题
1.填充格式错误
报的错误:ValueError: Data must be aligned to block boundary in ECB mode
解决思路:填充函数,使被加密数据的字节码长度是block_size的整数倍
实现代码:
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
entext = text + (chr(add) * add)
return entext
2.传入类型错误
TypeError: Object type <class 'str'> cannot be passed to C code
经过Debug发现,是因为传入参数的参数类型存在问题,需要更换为 bytearray , 也就是传入的key的类型错误:
import base64
import json
import requests
from Crypto.Cipher import AES
class EncryptDate:
def __init__(self, key):
# self.key = key # 一开始传入的初始化密钥
self.key = key.encode("utf-8") # 更新之后传入的初始化密钥
self.length = AES.block_size # 初始化数据块大小
self.aes = AES.new(self.key, AES.MODE_ECB) # 初始化
四、安装导入的第三方库
由于 pycrypto 已经停止维护很长时间,所以windows下切换成切换为pycryptodome,Linux下还是不变
pycryptodome