python3.7.2 AES加解密实现

#-*-coding:utf-8-*-
import Crypto.Cipher.AES
import Crypto.Random
import base64
import binascii

# AES加解密类
class Cipher_AES:
    cipher = getattr(Crypto.Cipher, "AES")
    pad = {"default": lambda x, y: x + (y - len(x) % y) * " ".encode("utf-8"),
           "PKCS5Padding": lambda x, y: x + (y - len(x) % y) * chr(y - len(x) % y).encode("utf-8")}
    unpad = {"default": lambda x: x.rstrip(),
             "PKCS5Padding": lambda x: x[:-ord(x[-1])]}
    encode = {"base64": base64.encodebytes,
              "hex": binascii.b2a_hex}
    decode = {"base64": base64.decodebytes,
              "hex": binascii.a2b_hex}

    def __init__(self, key=None, iv=None, cipher_method=None, pad_method="default", code_method=None):
        self.__key = key if key else "abcdefgh12345678"  # 密钥(长度必须为16、24、32)
        self.__iv = iv if iv else Crypto.Random.new().read(Cipher_AES.cipher.block_size)  # 向量(长度与密钥一致,ECB模式不需要)
        self.__cipher_method = cipher_method.upper() if cipher_method and isinstance(cipher_method, str) else "MODE_ECB"  # 加密方式,["MODE_ECB"|"MODE_CBC"|"MODE_CFB"]等
        self.__pad_method = pad_method  # 填充方式
        self.__code_method = code_method  # 编码方式,目前只有"base64"、"hex"两种
        if self.__cipher_method == "MODE_CBC":
            self.__cipher = Cipher_AES.cipher.new(self.__key.encode("utf-8"), Cipher_AES.cipher.MODE_CBC,
                                                  self.__iv.encode("utf-8"))
        else:
            self.__cipher = Cipher_AES.cipher.new(self.__key.encode("utf-8"), Cipher_AES.cipher.MODE_ECB)

    def __getitem__(self, item):
        def get3value(item):
            return item.start, item.stop, item.step

        type_, method, _ = get3value(item)
        dict_ = getattr(Cipher_AES, type_)
        return dict_[method] if method in dict_ else dict_["default"]

    def encrypt(self, text):
        cipher_text = b"".join([self.__cipher.encrypt(i) for i in self.text_verify(text.encode("utf-8"))])
        encode_func = Cipher_AES.encode.get(self.__code_method)
        if encode_func:
            cipher_text = encode_func(cipher_text)
        return cipher_text.decode("utf-8").rstrip()

    def decrypt(self, cipher_text):
        cipher_text = cipher_text.encode("utf-8")
        decode_func = Cipher_AES.decode.get(self.__code_method)
        if decode_func:
            cipher_text = decode_func(cipher_text)
        return self.pad_or_unpad("unpad", self.__cipher.decrypt(cipher_text).decode("utf-8"))

    def text_verify(self, text):
        while len(text) > len(self.__key):
            text_slice = text[:len(self.__key)]
            text = text[len(self.__key):]
            yield text_slice
        else:
            if len(text) == len(self.__key):
                yield text
            else:
                yield self.pad_or_unpad("pad", text)

    def pad_or_unpad(self, type_, contents):
        lambda_func = self[type_: self.__pad_method]
        return lambda_func(contents, len(self.__key)) if type_ == "pad" else lambda_func(contents)

# 主函数
if __name__ == '__main__':
    key = "fAEFfrTSCCP3uqZj"
    iv = "RandomInitVector"
    text = "hello world"
    cipher_method = "MODE_CBC"
    pad_method = "PKCS5Padding"
    code_method = "base64"
    # 加密
    encObj = Cipher_AES(key, iv, cipher_method, pad_method, code_method)
    cipher_text = encObj.encrypt(text)
    print(cipher_text)
    # 解密
    decObj = Cipher_AES(key, iv, cipher_method, pad_method, code_method)
    text = decObj.decrypt(cipher_text)
    print(text)

*【注】如果你觉得此文不错,可以考虑打赏我哦,您的打赏将是我更新的最大动力,非常感谢。(打赏也是基于自愿原则的哦( ̄︶ ̄))

在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值