封装了一个AES加解密(电码本ECB模式)的类
from Crypto.Cipher import AES
import hashlib
import base64
import sys
if sys.version_info > (3, 0):
pad = lambda s, n: s + bytes(n * [n])
unpad = lambda s: s[0:-s[-1]]
else: # py2没有bytes类型
pad = lambda s, n: s + n * chr(n)
unpad = lambda s: s[0:-ord(s[-1])]
def md5_hex(text):
md5 = hashlib.md5()
md5.update(str(text).encode("utf-8"))
return md5.hexdigest()
class Cipher():
def __init__(self, key):
self.__key = md5_hex(key)
self.AEScipher = AES.new(self.__key.encode("utf-8"), AES.MODE_ECB)
self.BS = 16
def get_key(self):
return self.__key
# AES加密并base64编码(输入为字符串,输出为base64编码后的字符串)
def encrypt_b64(self, data):
# 填充成16字节的倍数(假设缺n个字节,就填充n个二进制n)
offset_num = self.BS - len(data.encode("utf-8")) % self.BS # 需要补齐的位数;encode后才能正确计算包含中文的字符串长度
pad = lambda s, n: s + n * chr(n)
encrData = self.AEScipher.encrypt(pad(data, offset_num).encode("utf-8"))
encrData = base64.b64encode(encrData)
return encrData.decode()
# base64解码并AES解密(输入为base64编码的字符串/bytes,输出为字符串)
def decrypt_b64(self, encrData):
encrData = base64.b64decode(encrData)
# 删除填充的字节(最后一个字节的二进制数,就是填充的字节数)
if len(encrData) % self.BS != 0:
print('密文错误:长度不是%d倍数' % self.BS)
return ''
decrData = self.AEScipher.decrypt(encrData)
decrData = unpad(decrData)
return decrData.decode("utf-8")
# AES加密(py3输入输出为bytes)
def encrypt(self, data):
# 填充成16字节的倍数(假设缺n个字节,就填充n个二进制n)
offset_num = self.BS - len(data) % self.BS # 需要补齐的位数
encrData = self.AEScipher.encrypt(pad(data, offset_num))
return encrData
# AES解密(py3输入输出为bytes)
def decrypt(self, encrData):
# 删除填充的字节(最后一个字节的二进制数,就是填充的字节数)
if len(encrData) % self.BS != 0:
print('密文错误:长度不是%d倍数' % self.BS)
return ''
decrData = self.AEScipher.decrypt(encrData)
decrData = unpad(decrData)
return decrData