import base64 from Crypto.Cipher import AES
class AesEcbCrypt(): def __init__(self, key): self.key = key
def pkcs5padding(self, data): return self.pkcs7padding(data, 8)
def pkcs7padding(self, data, block_size=16): if type(data) != bytearray and type(data) != bytes: raise TypeError("仅支持 bytearray/bytes 类型!") pl = block_size - (len(data) % block_size) return data + bytearray([pl for i in range(pl)]) def encrypt(self, data): data = self.pkcs7padding(data, 16) return AES.new(self.key, AES.MODE_ECB).encrypt(data)
def decrypt(self, data): aes = AES.new(self.key, AES.MODE_ECB) decrypt_text = aes.decrypt(data) return decrypt_text[:-int(decrypt_text[-1])]
key = "abcdefghij123456".encode('utf-8') aes = AesEcbCrypt(key) text = "aaaaaaaa" en_byte = aes.encrypt(text.encode()) print("密文(HEX):", base64.standard_b64encode(en_byte).decode('utf-8')) de_byte = aes.decrypt(en_byte) print("明文:", de_byte.decode())
|