import os from cryptography.fernet import Fernet def generate_and_save_key(key_file_path): # 生成对称密钥 key = Fernet.generate_key() # 将密钥保存到文件中 with open(key_file_path, 'wb') as key_file: key_file.write(key) return key def encrypt_file(file_path, key): with open(file_path, 'rb') as file: plaintext = file.read() cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt(plaintext) with open(file_path + '.encrypted', 'wb') as encrypted_file: encrypted_file.write(cipher_text)