please add detailed comments to this code: from cryptography.fernet import Fernet…
- User
please add detailed comments to this code: from cryptography.fernet import Fernet
input_file_path = r"C:\Users\adam\Desktop\note1.txt" encrypted_file_path = r"C:\Users\adam\Desktop\note2.txt" decrypted_file_path = r"C:\Users\adam\Desktop\note3.txt" key_file_path = r"C:\Users\adam\Desktop\key.key" # Path to save the key
def generate_and_save_key(): key = Fernet.generate_key() with open(key_file_path, "wb") as key_file: key_file.write(key) return key
def load_key(): return open(key_file_path, "rb").read()
def encrypt_file(file_path, encrypted_file_path, key): f = Fernet(key) with open(file_path, "rb") as file: file_data = file.read() encrypted_data = f.encrypt(file_data) with open(encrypted_file_path, "wb") as file: file.write(encrypted_data)
def decrypt_file(encrypted_file_path, decrypted_file_path, key): f = Fernet(key) with open(encrypted_file_path, "rb") as file: encrypted_data = file.read() decrypted_data = f.decrypt(encrypted_data) with open(decrypted_file_path, "wb") as file: file.write(decrypted_data)
Generate and save the key only once
generate_and_save_key()
Load the key
key = load_key()
Encrypt the file
encrypt_file(input_file_path, encrypted_file_path, key) print(f"{input_file_path} has been encrypted.")
Decrypt the file
decrypt_file(encrypted_file_path, decrypted_file_path, key) print(f"{decrypted_file_path} has been decrypted.")
- Assistant