AES padding 加解密方法
- 目前网络上、论坛上大多数均是 自写 lambda 函数实现如下所示
from Crypto.Cipher import AES
import base64
class AEScoder():
def __init__(self):
self.__encryptKey = "iEpSxImA0vpMUAabsjJWug=="
self.__key = base64.b64decode(self.__encryptKey)
def encrypt(self,data):
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
cipher = AES.new(self.__key, AES.MODE_ECB)
encrData = cipher.encrypt(pad(data))
return encrData
def decrypt(self,encrData):
unpad = lambda s: s[0:-s[-1]] [此处]
cipher = AES.new(self.__key, AES.MODE_ECB)
decrData = unpad(cipher.decrypt(encrData))
return decrData.decode('utf-8')
- 其实 Crypto 模块中已经集成了我们使用的填充方式 如下:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
import base64
class AEScoder():
def __init__(self):
self.__encryptKey = "iEpSxImA0vpMUAabsjJWug=="
self.__key = base64.b64decode(self.__encryptKey)
def encrypt(self,data):
cipher = AES.new(self.__key, AES.MODE_ECB)
encrData = cipher.encrypt(pad(data,16,'pkcs7'))
return encrData
def decrypt(self,encrData):
cipher = AES.new(self.__key, AES.MODE_ECB)
decrData = unpad(cipher.decrypt(encrData),16,'pkcs7')
return decrData.decode('utf-8')