Python AES CBC 加密解密

博客围绕Python开发语言展开,虽未给出具体内容,但可知与Python这一开发语言相关,Python在后端开发等众多信息技术领域应用广泛。

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

Python AES CBC 加密解密

import base64
import cv2
import numpy as np
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import json

def cv2bytes(im):
    '''cv2转二进制图片
    :param im: cv2图像,numpy.ndarray
    :return: 二进制图片数据,bytes
    '''
    return np.array(cv2.imencode('.png', im)[1]).tobytes()

class AESUtilECB:
    def __init__(self, key):
        self.pad_length = AES.block_size
        self.key = key

    def encryt(self, data):
        """
        :param data: 二进制图片数据
        :return: 经过aes加密和base64编码后的图像数据
        """
        data = data.encode('utf-8')
        cipher = AES.new(self.key.encode('utf-8'), AES.MODE_ECB,)
        data = pad(data, 16, style='pkcs7')
        # data = data.encode('utf-8')
        msg = cipher.encrypt(data)
        msg = base64.b64encode(msg)
        msg = msg.decode('utf-8')
        return msg

    def decrypt(self, enStr):
        cipher = AES.new(self.key.encode('utf-8'), AES.MODE_ECB, )
        decryptByts = base64.b64decode(enStr)
        msg = cipher.decrypt(decryptByts)
        msg = msg.strip(b'\x0f')
        return msg.decode('utf-8')

class AESUtilCBC:
    def __init__(self, key, iv):
        self.pad_length = AES.block_size
        self.key = key
        self.iv = iv

    def encryt(self, data):
        """
        :param data: 二进制图片数据
        :return: 经过aes加密和base64编码后的图像数据
        """
        data = data.encode('utf-8')
        cipher = AES.new(self.key.encode('utf-8'), AES.MODE_CBC, self.iv.encode('utf-8'))
        data = pad(data, 16, style='pkcs7')
        # data = data.encode('utf-8')
        msg = cipher.encrypt(data)
        msg = base64.b64encode(msg)
        msg = msg.decode('utf-8')
        return msg

    def decrypt(self, enStr):
        cipher = AES.new(self.key.encode('utf-8'), AES.MODE_CBC, self.iv.encode('utf-8') )
        decryptByts = base64.b64decode(enStr)
        msg = cipher.decrypt(decryptByts)
        msg = msg.strip(b'\x0f')
        return msg.decode('utf-8')

if __name__ == "__main__":
    text = "{\"token\":\"0e84b297-d8f2-4779-b7f1-60966ed19ce1\"}"
    # text = json.dumps({"token":"0e84b297-d8f2-4779-b7f1-60966ed19ce1"})
    key = "DigiDigiDigiDigi"
    iv = "1234567887654321"
    aes = AESUtilCBC(key,iv)
    encrypt_res = aes.encryt(text)
    print(encrypt_res)
    decrypt_res = aes.decrypt(encrypt_res)
    print(decrypt_res)

输出结果

text {"token":"0e84b297-d8f2-4779-b7f1-60966ed19ce1"}
encrypt_res NVyP1JRriAErG7oHVNAAvSHcaUl/DnBLpHaWRSTX+ou8edvMnzF6aMiQyLukPbFUAAsXSR3EMo068sOYJMVnZw==
decrypt_res {"token":"0e84b297-d8f2-4779-b7f1-60966ed19ce1"}
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、付费专栏及课程。

余额充值