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

Python实现简单的文件加密解密程序

发布时间:2023-12-04 08:15:51

下面是一个简单的文件加密解密程序的实现以及使用例子。

1. 文件加密解密程序实现

import os
from cryptography.fernet import Fernet

# 生成密钥
def generate_key():
    return Fernet.generate_key()

# 加密文件
def encrypt_file(key, input_file, output_file):
    fernet = Fernet(key)
    with open(input_file, 'rb') as file:
        plaintext = file.read()
    encrypted_text = fernet.encrypt(plaintext)
    with open(output_file, 'wb') as file:
        file.write(encrypted_text)

# 解密文件
def decrypt_file(key, input_file, output_file):
    fernet = Fernet(key)
    with open(input_file, 'rb') as file:
        encrypted_text = file.read()
    decrypted_text = fernet.decrypt(encrypted_text)
    with open(output_file, 'wb') as file:
        file.write(decrypted_text)

上述代码使用了cryptography库中的Fernet模块来实现文件的加密和解密。通过generate_key函数可以生成一个随机的密钥。encrypt_file函数接受密钥、输入文件和输出文件作为参数,使用Fernet对象加密输入文件,并将加密后的内容写入到输出文件中。decrypt_file函数接受密钥、输入文件和输出文件作为参数,使用Fernet对象解密输入文件,并将解密后的内容写入到输出文件中。

2. 文件加密解密程序使用例子

# 生成密钥
key = generate_key()

# 加密文件
input_file = 'test.txt'
encrypted_file = 'encrypted_test.txt'
encrypt_file(key, input_file, encrypted_file)
print('文件加密完成')

# 解密文件
decrypted_file = 'decrypted_test.txt'
decrypt_file(key, encrypted_file, decrypted_file)
print('文件解密完成')

上述代码首先生成一个密钥,然后使用该密钥对文件test.txt进行加密,并将加密后的内容写入到encrypted_test.txt文件中。接着使用密钥对加密后的文件进行解密,并将解密后的内容写入到decrypted_test.txt文件中。输出语句在文件加密和解密完成后显示相应的提示信息。

以上是一个简单的文件加密解密程序的实现以及使用例子。你可以根据自己的需求进行修改和扩展。