python AES加密 ECB PKCS5

class AesEbc16:  # 按块的大小, 一块一块的加密, 明文和密文长度一样
  def __init__(self):
    self.key = b"zMOmOzkt76WUW5mj"  # 加密和解密用同一个秘钥, 长度为 每块的长度
    self.mode = AES.MODE_ECB  # ECB加密模式, 也是默认的模式, 创建AES加密对象时可以不写
    self.block_size = 16  # 每块16的bytes长度,  即是PKCS5 这种方式,  和秘钥长度一致

  def plaintext(self, s_text):  # 转bytes 并 补齐为16的倍数

    b_text = str.encode(s_text)
    count = len(b_text)
    # text不是16的倍数那就补足为16的倍数
    add_count = self.block_size - (count % self.block_size)
    s_plaintext = s_text + (' ' * add_count)
    b_plaintext = str.encode(s_plaintext)
    return b_plaintext

  def encrypt(self, str_text): # 加密
    aes_cipher = AES.new(self.key, self.mode) # ECB模式无需向量iv
    cipher_text = aes_cipher.encrypt(self.plaintext(str_text))
    return cipher_text

  def decrypt(self, b_text): # 解密
    aes_cipher = AES.new(self.key, self.mode)
    b_plaintext = aes_cipher.decrypt(b_text)
    return b_plaintext

猜你喜欢

转载自www.cnblogs.com/520zm/p/10645877.html