加密/解密 - AES

1.安装

首先安装pycryptodome

pip install pycryptodome

2.样例

from Crypto.Cipher import AES
import base64


class Pcrypt():
    def __init__(self, key):
        """

        :param key: 密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度. 目前AES-128足够用
        """
        self.key = key
        if len(key) <= 16:
            while len(key) < 16:
                key += '\0'
        else:
            raise Exception('超出key长度限制: 0-16位')
        self.key = str.encode(key)

        self.aes = AES.new(self.key, AES.MODE_ECB)  # 初始化加密器
        self.mode = AES.MODE_CBC

    @staticmethod
    def add_to_16(text):
        """
        str不是16的倍数那就补足为16的倍数
        :param text:
        :return:
        """
        while len(text) % 16 != 0:
            text += '\0'
        return str.encode(text)  # 返回bytes

    def encrypt(self, text):
        """
        加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数
        :param text: 需要加密的字符串
        :return:
        """
        # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
        # 所以这里统一把加密后的字符串用base64转化
        return str(base64.encodebytes(self.aes.encrypt(self.add_to_16(text))), encoding='utf8').replace('\n', '')

    def decrypt(self, text):
        """

        :param text: 加密后的字符串
        :return:
        """
        # 解密后,去掉补足的'\0'用strip() 去掉
        return str(self.aes.decrypt(base64.decodebytes(bytes(text, encoding='utf8'))).rstrip(b'\0').decode("utf8"))


if __name__ == '__main__':
    key = 'lseafasefaew'
    pc = Pcrypt(key)
    e = pc.encrypt("8")
    print(e)
    d = pc.decrypt(e)
    print(d)


"""
4gRqBiLtjVqiGSSgemHF3w==
8
"""
posted @   灬无涯  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示