from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex import base64 from datetime import datetime import hashlib # https://www.cnblogs.com/qiufenzhiyue/articles/12191416.html def token() -> str: d1 = datetime.today() tokenStr = 'yss_bdc' + str(d1.month) + str(d1.day) + str(d1.weekday()+1) + str(d1.year) m = hashlib.md5() m.update(tokenStr.encode('ascii')) token_md5 = m.hexdigest() return token_md5[0:16] class AES_ECB: def __init__(self,key): self.key = key.encode('utf8') self.mode = AES.MODE_ECB # 生成加密器,参数密匙和模式,ECB需要偏移量 self.cryptor = AES.new(self.key, self.mode) @staticmethod def add_to_16(text): pad = 16 - len(text.encode('utf-8')) % 16 text = text + pad * chr(pad) return text.encode('utf-8') def encrypt(self,text): #预处理,填充明文为16的倍数 text = self.add_to_16(text) #加密,输出bytes类型 cipher_text = self.cryptor.encrypt(text) return b2a_hex(cipher_text).decode('utf-8') def decrypt(self,text): text_a = a2b_hex(text) hex_text = self.cryptor.decrypt(text_a).decode('utf8') #剔除尾部 return hex_text[0:-ord(hex_text[-1])] def encrypt(self, text): #预处理,填充明文为16的倍数 text = self.add_to_16(text) #加密,输出bytes类型 cipher_text = self.cryptor.encrypt(text) return b2a_hex(cipher_text).decode('utf-8') def decrypt_old(self,arr): text_a = a2b_hex(arr[1]) text_b = base64.b64decode(arr[0]) # base64解码 hex_text = self.cryptor.decrypt(text_a).decode('utf8') #剔除尾部 hex_text = hex_text[0:-ord(hex_text[-1])] base64_text = self.cryptor.decrypt(text_b).decode('utf8') base64_text = base64_text[0:-ord(base64_text[-1])] print('解密16进制密文:',arr[1],'->',hex_text) print('解密base64密文:', arr[0],'->',base64_text) if __name__ == '__main__': import os key = token() t = 'aaaaa' ase = AES_ECB(key) print(ase.encrypt(t)) ase.decrypt(ase.encrypt(t))