AES加密与解密

from Cryptodome.Cipher import  AES
from Cryptodome import  Random
import  binascii

class MyAES(object):
    def __init__(self,key,iv=None,mode=AES.MODE_CFB):
        self.key =key
        self.mode = mode
        if iv:
            self.iv = iv
        else:
            self.iv =Random.new().read(AES.block_size)
    def encrypt(self,data):
        if isinstance(data,str):
            data =data.encode()
        aes = AES.new(self.key,self.mode,self.iv)
        result = aes.encrypt(data)
        return binascii.b2a_hex(result)

    def decrypt(self,data):
        if isinstance(data,str):
            data =data.encode()

        aes = AES.new(self.key,self.mode,self.iv)
        result = aes.decrypt(binascii.a2b_hex(data))
        return result.decode()




if __name__ == '__main__':
    key = b'abcdefgh12345678'
    a = MyAES(key)
    data = ('我是神')
    encrypt_data = a.encrypt(data)
    print('加密的数据:',encrypt_data)
    iv = a.iv
    decrypt_data = a.decrypt(encrypt_data)
    print('解密后的数据',decrypt_data)

你可能感兴趣的:(AES加密与解密)