在这个实例中,我们将创建一个简单的文件加密/解密程序,使用对称加密算法来加密和解密文件内容。这里我们使用cryptography库来实现加密/解密功能。请确保你已经安装了cryptography库,如果没有安装,可以通过以下命令来安装:
bash Copy code pip install cryptography 下面是文件加密/解密的Python程序:
python Copy code from cryptography.fernet import Fernet
def generate_key(): return Fernet.generate_key()
def encrypt_file(file_path, key): with open(file_path, 'rb') as file: data = file.read()
fernet = Fernet(key)
encrypted_data = fernet.encrypt(data)
with open(file_path, 'wb') as file:
file.write(encrypted_data)
def decrypt_file(file_path, key): with open(file_path, 'rb') as file: encrypted_data = file.read()
fernet = Fernet(key)
decrypted_data = fernet.decrypt(encrypted_data)
with open(file_path, 'wb') as file:
file.write(decrypted_data)
if name == "main": key = generate_key()
# 要加密的文件路径
file_path_to_encrypt = "example.txt"
encrypt_file(file_path_to_encrypt, key)
print("文件加密完成!")
# 要解密的文件路径
file_path_to_decrypt = "example.txt"
decrypt_file(file_path_to_decrypt, key)
print("文件解密完成!")
在上述代码中,我们使用Fernet对称加密算法来生成加密密钥(key)。然后,我们使用这个密钥来加密和解密文件内容。
请将要加密的文件路径替换为file_path_to_encrypt,运行程序后,它会加密指定的文件内容并输出"文件加密完成!"。然后,再次运行程序,它将解密已加密的文件内容并输出"文件解密完成!"。
请注意,为了保证数据的安全性,密钥(key)需要妥善保存,最好不要将其硬编码在程序中。密钥的管理和保护是加密系统的重要部分。