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

使用Python编写一个简单的文件加密程序

发布时间:2023-12-04 17:46:49

下面是一个使用Python编写的简单文件加密程序:

import os
from cryptography.fernet import Fernet

def generate_key():
    key = Fernet.generate_key()
    with open("encryption_key.key", "wb") as key_file:
        key_file.write(key)

def load_key():
    with open("encryption_key.key", "rb") as key_file:
        key = key_file.read()
    return key

def encrypt_file(file_path, key):
    f = Fernet(key)
    with open(file_path, "rb") as file:
        original_content = file.read()
    encrypted_content = f.encrypt(original_content)
    with open(file_path, "wb") as file:
        file.write(encrypted_content)

def decrypt_file(file_path, key):
    f = Fernet(key)
    with open(file_path, "rb") as file:
        encrypted_content = file.read()
    decrypted_content = f.decrypt(encrypted_content)
    with open(file_path, "wb") as file:
        file.write(decrypted_content)

# 生成一个新的密钥文件
generate_key()

# 加载密钥文件
key = load_key()

# 加密文件
file_path = "example.txt"
encrypt_file(file_path, key)
print(f"{file_path}已加密。")

# 解密文件
decrypt_file(file_path, key)
print(f"{file_path}已解密。")

这个程序使用了cryptography库来实现文件的加密和解密功能。首先,我们需要生成一个新的密钥文件,并且保存在encryption_key.key中。然后,我们可以使用load_key函数加载密钥文件。接下来,使用encrypt_file函数来加密指定文件,并使用decrypt_file函数来解密文件。

在使用这个程序之前,需要先安装cryptography库,可以使用以下命令进行安装:

pip install cryptography

使用示例:

假设我们有一个名为example.txt的文件,首先运行程序生成密钥文件,然后使用这个密钥文件对example.txt进行加密,最后再使用相同的密钥文件对加密后的example.txt进行解密。

程序输出:

example.txt已加密。
example.txt已解密。

经过加密和解密后的example.txt与原始文件完全一致。需要注意的是,为了保证安全性,密钥文件需要妥善保存,最好不要与加密的文件放在同一个目录中。