python aes加解密

本文详细介绍了一种使用Python实现的AES加密解密方法,通过CBC模式和自定义密钥及初始化向量,实现了字符串的加密与解密过程。文章提供了完整的代码示例,包括加密前的填充操作和解密后的处理。

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

方案一

  1. 依赖python == 3.8.10
  2. 依赖包:pycryptodome == 3.22.0
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64


class AESCipher(object):
    def __init__(self, key):
        self.encoder = 'utf-8'
        self.key = key.encode(self.encoder)
        # 加密模式
        self.mode = AES.MODE_ECB
        # 补全方式
        self.style = 'pkcs7'
        # 创建 AES 对象
        self.aes = AES.new(self.key, self.mode)

    def encrypt(self, text):
        """
        加密
        """
        # 填充
        pad_text = pad(text.encode(self.encoder), AES.block_size, style=self.style)
        # 加密
        encrypt_text = self.aes.encrypt(pad_text)

        encrypt_text_str = str(base64.encodebytes(encrypt_text), encoding=self.encoder)
        return encrypt_text_str.replace('\n', '')

    def decrypt(self, text):
        """
        解密
        """
        # 将 base64 编码的密文解码为字节
        ciphertext = base64.b64decode(text)
        # 解密
        decrypted_data = self.aes.decrypt(ciphertext)
        # 去除填充
        plaintext = unpad(decrypted_data, AES.block_size, style=self.style)

        return plaintext.decode('utf-8')


text = '这只是一个测试明文, this is just a test'

ase = AESCipher(key='12345ABCDE654321')
# 加密
encrypt_text = ase.encrypt(text)
print(encrypt_text)

# 解密
decrypt_text = ase.decrypt(encrypt_text)
print(decrypt_text)
print(text == decrypt_text)

方案二

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


class AesCode(object):
    def __init__(self, key='1234567812345678', iv='1234567812345678', mode=AES.MODE_CBC):
        self.key = key.encode('utf-8')
        self.iv = iv.encode('utf-8')
        self.mode = mode

    @staticmethod
    def bytePad(text, byteAlignLen=16):
        count = len(text)
        mod_num = count % byteAlignLen
        if mod_num == 0:
            return text
        add_num = byteAlignLen - mod_num
        return text + chr(add_num).encode('utf8') * add_num

    def encode(self, text):
        aes = AES.new(key=self.key, iv=self.iv, mode=self.mode)

        enc_text=self.bytePad(text.encode('utf-8'),16)
        p = aes.encrypt(enc_text)
        return b2a_hex(p).decode('utf8')

    def decode(self, text):
        aes = AES.new(key=self.key, iv=self.iv, mode=self.mode)

        text = text.replace('*屏蔽的关键字*', '')
        hex_text = a2b_hex(text.strip())
        pad_text = self.bytePad(hex_text, 16)
        res = aes.decrypt(pad_text)
        return res.decode('utf8')

aes = AesCode()

AES(Advanced Encryption Standard)是高级加密标准的缩写,它是对称加密算法中的一种。Python中有多个库能够实现AES加密和解密操作,其中`pycryptodome`是一个常用的选择。 ### 安装 pycryptodome 如果你还没有安装这个库的话,请先用pip安装: ```bash pip install pycryptodome ``` ### Python AES 加密解密示例代码 以下是一段简单的例子展示如何在Python中使用AES来进行字符串的加密与解密: #### 导入必要的模块 首先导入所需的类和方法: ```python from Crypto.Cipher import AES import base64 # 用于处理填充 from Crypto.Util.Padding import pad, unpad ``` #### 设置加解密使用的函数 接下来定义两个辅助函数用来执行实际的加密和解密逻辑: ```python def encrypt(plain_text, key): # 创建一个基于给定key的新AES Cipher实例 cipher = AES.new(key.encode('utf8'), AES.MODE_CBC) # 对明文进行PKCS7填充并编码为bytes类型后再加密 padded_plaintext = plain_text.encode('utf-8') ct_bytes = cipher.encrypt(pad(padded_plaintext, AES.block_size)) # 将IV(初始化向量)附加上去以便后续正确解码;这里我们简单地把它base64转成string连在一起返回。 iv_base64 = base64.b64encode(cipher.iv).decode('utf-8') ct_base64 = base64.b64encode(ct_bytes).decode('utf-8') return f"{iv_base64}:{ct_base64}" def decrypt(encryption_str, key): try: # 解析出IV部分以及真实的cipher text部分. iv_base64, ct_base64 = encryption_str.split(':') # 分别将两部分内容从base64恢复回来得到原本的数据形式。 iv = base64.b64decode(iv_base64) ct = base64.b64decode(ct_base64) # 使用相同的key创建一个新的AES Cipher对象,并传入之前保存下来的IV作为参数之一重新构造Cipher instance。 cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, iv=iv) decrypted_data = unpad(cipher.decrypt(ct), AES.block_size) return decrypted_data.decode('utf-8') except Exception as e: print(f"Error occurred during decryption - {str(e)}") raise ValueError("Failed to Decrypt Data") ``` 请注意,在上面的例子中,我们需要确保提供的`key`长度符合AES的要求——即必须为16字节、24字节或32字节长(对应于AES-128, AES-192 和 AES-256)。如果您的键不符合这些尺寸,则需要对其进行适当的截断或者扩展以满足需求。 #### 测试功能 现在我们可以尝试一下这两个新构建的方法了! ```python if __name__ == "__main__": secret_key = "thisisaverysecret" message_to_encrypt = "Hello World!" encrypted_message = encrypt(message_to_encrypt, secret_key) print("Encrypted:", encrypted_message) decrypted_message = decrypt(encrypted_message, secret_key) print("Decrypted:", decrypted_message) ``` 以上就是关于Python中的AES加密/解密的基本介绍啦~希望这对您有所帮助!如果您还有其他疑问或其他方面的需求,请随时告诉我哦。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值