欢迎访问宙启技术站
智能推送

Python代码示例:使用Crypto.Cipher.AES.MODE_CBC加密文件

发布时间:2023-12-11 07:19:30

使用Crypto.Cipher.AES.MODE_CBC加密文件的Python代码示例如下:

from Crypto.Cipher import AES
import os

def encrypt_file(key, input_file, output_file):
    # 生成一个16字节的随机初始向量
    iv = os.urandom(16)

    # 创建AES加密器,使用CBC模式和随机初始向量
    cipher = AES.new(key, AES.MODE_CBC, iv)

    # 打开输入文件和输出文件
    with open(input_file, 'rb') as file_in:
        with open(output_file, 'wb') as file_out:
            # 写入初始向量
            file_out.write(iv)

            # 逐块读取并加密输入文件的内容,写入输出文件
            while True:
                chunk = file_in.read(16)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    # 如果块长度不是16的倍数,则需要进行填充
                    chunk += b' ' * (16 - len(chunk) % 16)
                file_out.write(cipher.encrypt(chunk))

def decrypt_file(key, input_file, output_file):
    # 打开输入文件和输出文件
    with open(input_file, 'rb') as file_in:
        with open(output_file, 'wb') as file_out:
            # 读取初始向量
            iv = file_in.read(16)

            # 创建AES解密器,使用CBC模式和初始向量
            cipher = AES.new(key, AES.MODE_CBC, iv)

            # 逐块读取并解密输入文件的内容,写入输出文件
            while True:
                chunk = file_in.read(16)
                if len(chunk) == 0:
                    break
                file_out.write(cipher.decrypt(chunk))

# 示例用法
key = b'0123456789abcdef'  # 16字节的加密密钥
input_file = 'plaintext.txt'  # 待加密的文件
encrypted_file = 'encrypted.bin'  # 加密后的文件
decrypted_file = 'decrypted.txt'  # 解密后的文件

# 加密文件
encrypt_file(key, input_file, encrypted_file)

# 解密文件
decrypt_file(key, encrypted_file, decrypted_file)

以上代码使用了Crypto.Cipher.AES模块中的AES类,并指定了MODE_CBC模式。加密过程中使用了一个随机生成的16字节初始向量,在加密和解密过程中都需要使用同一个密钥。使用encrypt_file函数可以加密一个文件,并将加密后的内容写入到输出文件中,使用decrypt_file函数可以解密一个文件,并将解密后的内容写入到输出文件中。

需要注意的是,如果输入文件的长度不是16的倍数,则在加密过程中需要进行填充,这个示例中是使用空格进行填充。解密过程会自动去除填充的内容。另外,加密后的内容会保存为二进制文件,解密后的内容会保存为文本文件。

为了使用上述代码,需要安装pycryptodome模块,可以通过pip install pycryptodome命令进行安装。