python进阶(23)用Python实现AES_ECB_PKCS5加密


前言

AES加密的模式有很多种,下面来介绍ECB模式的加密解密

import base64
from Crypto.Cipher import AES


class AESECB:
    def __init__(self, key):
        self.key = key  # 加密密钥
        self.mode = AES.MODE_ECB  # 设置为ECB模式
        self.bs = 16  # block size
        self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    def encrypt(self, text):
        generator = AES.new(self.key, self.mode)  # ECB模式无需向量iv
        crypt = generator.encrypt(self.PADDING(text).encode('utf-8'))
        crypted_str = base64.b64encode(crypt).decode('utf-8')
        return crypted_str

    def decrypt(self, text):
        generator = AES.new(self.key, self.mode)  # ECB模式无需向量iv
        decrpyt_bytes = base64.b64decode(text)
        meg = generator.decrypt(decrpyt_bytes).decode('utf-8')
        return meg[:-ord(meg[-1])]


if __name__ == '__main__':
    aes = AESECB('1234567890abcdef')
    print(aes.encrypt('111111'))
    print(aes.decrypt('rfTzn9WjsDFbK262m0k4xg=='))

结果:

rfTzn9WjsDFbK262m0k4xg==
111111