Python:AES加密

该博客介绍了如何在Python中使用pycrypto和pycryptodome库进行AES-CBC模式的加密与解密操作。首先讲解了在不同操作系统下安装相应库的方法,然后通过一个名为AesCbc的类展示了加密和解密的详细步骤,包括秘钥、初始向量的设定,以及如何处理不足16位倍数的文本。此外,还提供了静态方法用于填充到16位,并展示了加密结果如何转换为16进制字符串以便存储和传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# linux系统 pip install pycrypto
# Windows pip3 install -i https://pypi.douban.com/simple pycryptodome 找到文件所在目录 将文件夹名"crypto" 修改为"Crypto"
from Crypto.Cipher import AES
class AesCbc:
    __instance = None

    # 单例模式
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        #  key:秘钥,大小为16byte/24byte/32byte----AES-128/AES-192/AES-256/
        self.key = 'xiwenr&dstaTGpRw'.encode('utf-8')
        #  vi:初始向量,大小为16byte
        self.iv = b'xiwenr&drhGW5hN3'
        self.mode = AES.MODE_CBC

    # 如果text不足16位的倍数就用空格补足为16位
    @staticmethod
    def add_to_16(text):
        if len(text.encode('utf-8')) % 16:
            add = 16 - (len(text.encode('utf-8')) % 16)
        else:
            add = 0
        text = text + ('\0' * add)
        return text.encode('utf-8')

    # 加密函数
    def encrypt(self, text):
        text = self.add_to_16(text)
        cryptos = AES.new(self.key, self.mode, self.iv)
        cipher_text = cryptos.encrypt(text)
        # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
        return b2a_hex(cipher_text).decode()

    # 解密后,去掉补足的空格用strip() 去掉
    def decrypt(self, text):
        cryptos = AES.new(self.key, self.mode, self.iv)
        plain_text = cryptos.decrypt(a2b_hex(text))
        return bytes.decode(plain_text).rstrip('\0')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值