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

在Python中使用Crypto.Cipher.Blowfish算法加密和解密文件

发布时间:2023-12-19 02:34:28

在Python中,我们可以使用Crypto.Cipher模块的Blowfish算法来加密和解密文件。Blowfish算法是一种对称密钥算法,可以使用相同的密钥进行加密和解密。下面是一个使用Blowfish算法加密和解密文件的示例代码:

from Crypto.Cipher import Blowfish
import os


def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
    if not out_filename:
        out_filename = in_filename + '.enc'

    # 创建一个Blowfish加密器
    cipher = Blowfish.new(key, Blowfish.MODE_ECB)

    # 获取文件大小
    file_size = os.path.getsize(in_filename)

    with open(in_filename, 'rb') as in_file:
        with open(out_filename, 'wb') as out_file:
            # 加密文件内容
            while True:
                chunk = in_file.read(chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 8 != 0:
                    # 如果chunk的长度不是8的倍数,则补充空格
                    chunk += b' ' * (8 - len(chunk) % 8)

                out_file.write(cipher.encrypt(chunk))

    return out_filename


def decrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
    if not out_filename:
        # 默认输出文件名为去除.enc的输入文件名
        out_filename = os.path.splitext(in_filename)[0]

    # 创建一个Blowfish解密器
    cipher = Blowfish.new(key, Blowfish.MODE_ECB)

    # 获取文件大小
    file_size = os.path.getsize(in_filename)

    with open(in_filename, 'rb') as in_file:
        with open(out_filename, 'wb') as out_file:
            # 解密文件内容
            while True:
                chunk = in_file.read(chunksize)
                if len(chunk) == 0:
                    break

                out_file.write(cipher.decrypt(chunk))

    return out_filename


# 测试加密
key = b'This is a key123'
in_file = 'test.txt'
out_file = encrypt_file(key, in_file)
print(f'{in_file}加密后的文件名为:{out_file}')

# 测试解密
in_file = out_file
out_file = decrypt_file(key, in_file)
print(f'{in_file}解密后的文件名为:{out_file}')

在上面的例子中,我们创建了两个函数encrypt_filedecrypt_file来分别实现文件的加密和解密操作。这两个函数接受一个密钥(以字节字符串形式传递)和输入文件名作为参数,并可选地指定输出文件名,默认情况下输出文件名为输入文件名加上'.enc'后缀(加密操作)或去除'.enc'后缀(解密操作)。另外,还可以通过chunksize参数指定每次从文件中读取的字节数,默认为64KB。

在上述示例中,我们加密了名为'test.txt'的文件,并将加密后的文件保存在'test.txt.enc'中。然后,我们对该加密文件进行解密,并将得到的解密数据保存为'test.txt'。