以下是一个使用Python实现的文件加密和解密程序的示例:
import os from cryptography.fernet import Fernet # 生成加密密钥 def generate_key(): key = Fernet.generate_key() with open("key.key", "wb") as key_file: key_file.write(key) # 加载密钥 def load_key(): return open("key.key", "rb").read() # 加密文件 def encrypt_file(file_path): key = load_key() cipher = Fernet(key) with open(file_path, "rb") as file: file_data = file.read() encrypted_data = cipher.encrypt(file_data) with open(file_path, "wb") as encrypted_file: encrypted_file.write(encrypted_data) # 解密文件 def decrypt_file(file_path): key = load_key() cipher = Fernet(key) with open(file_path, "rb") as encrypted_file: encrypted_data = encrypted_file.read() decrypted_data = cipher.decrypt(encrypted_data) with open(file_path, "wb") as decrypted_file: decrypted_file.write(decrypted_data) # 加密整个目录下的文件 def encrypt_directory(directory_path): file_list = os.listdir(directory_path) for file_name in file_list: file_path = os.path.join(directory_path, file_name) if os.path.isfile(file_path): encrypt_file(file_path) # 解密整个目录下的加密文件 def decrypt_directory(directory_path): file_list = os.listdir(directory_path) for file_name in file_list: file_path = os.path.join(directory_path, file_name) if os.path.isfile(file_path): decrypt_file(file_path) # 使用示例 # 生成密钥 generate_key() # 加密单个文件 encrypt_file("example.txt") # 解密单个文件 decrypt_file("example.txt") # 加密整个目录 encrypt_directory("directory_path") # 解密整个目录 decrypt_directory("directory_path")
上述代码使用了cryptography库来实现文件的加密和解密。在代码中,先定义了两个函数generate_key和load_key,分别用于生成密钥和加载密钥。然后,使用生成的密钥创建加密器和解密器对象,并使用这些对象对文件进行加密和解密操作。最后,提供了两个函数encrypt_directory和decrypt_directory来分别加密和解密整个目录下的文件。在示例中,使用了example.txt文件以及一个名为directory_path的目录来进行加密和解密操作。