python3实现CryptoJS AES加密算法

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import base64


class AesCrypt:
    def __init__(self, __key):
        self.key = __key.encode('utf8')
        self.mode = AES.MODE_ECB  # 模式可以更改为MODE_CBC需要添加vi

        # 生成加密器,参数:密匙,模式
        self.cryptor = AES.new(self.key, self.mode)

    @staticmethod
    def add_to_16(text):
        pad = 16 - len(text.encode('utf-8')) % 16
        text = text + pad * chr(pad)
        return text.encode('utf-8')

    def encrypt(self, text, base=16):
        """  加密方法
        :param text: 需要加密的文本
        :param base:  需要加密的类型
        :return:加密完的字符串
        """
        # 预处理,填充明文为16的倍数
        text = self.add_to_16(text)

        # 加密,输出bytes类型
        cipher_text = self.cryptor.encrypt(text)
        if base == 16:
            # 返回16进制密文
            return b2a_hex(cipher_text).decode('utf-8')
        elif base == 64:
            # 返回base64密文
            return base64.b64encode(cipher_text).decode('utf-8')

    def decrypt(self, ciphertext, base=16):
        if base == 16:
            # 解密16进制密文
            text = a2b_hex(ciphertext)
        elif base == 64:
            # 解密base64密文
            text = base64.b64decode(ciphertext)  # base64解码
        else:
            raise Exception('不支持的编码')
        utf8_text = self.cryptor.decrypt(text).decode('utf8')
        return utf8_text[0:-ord(utf8_text[-1])]


if __name__ == '__main__':
    key = 'd5fdec7c7746261f'
    txt = '123456'
    ase = AesCrypt(key)
    print(ase.encrypt(txt))

    print(ase.decrypt('6e670907d658b6d35167cd2b41f3a565'))

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CtrlCV工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值