Preparing security example
I need to mention using pip install cryptography. I'll make sure to include potential security disclaimers, like keeping the key safe. It could feel like overkill to discuss compression or advanced topics, so I want to keep it simple. My focus will be on providing a complete, runnable example to help the user understand. Let's make sure to respond clearly and effectively! Below is a minimal, complete example of encrypting and decrypting files using Fernet from the cryptography library.
1. Install dependency
pip install cryptography
2. Python code
from cryptography.fernet import Fernet
def generate_key(key_path: str) -> bytes:
"""
Generate a new Fernet key and save it to key_path.
Returns the generated key.
"""
key = Fernet.generate_key()
with open(key_path, "wb") as key_file:
key_file.write(key)
return key
def load_key(key_path: str) -> bytes:
"""
Load a Fernet key from key_path.
"""
with open(key_path, "rb") as key_file:
return key_file.read()
def encrypt_file(input_path: str, output_path: str, key: bytes) -> None:
"""
Encrypt a file using the given Fernet key.
- input_path: path to the plaintext file
- output_path: path where the encrypted file will be written
- key: bytes key generated by Fernet.generate_key()
"""
f = Fernet(key)
with open(input_path, "rb") as file:
data = file.read()
encrypted_data = f.encrypt(data)
with open(output_path, "wb") as file:
file.write(encrypted_data)
def decrypt_file(input_path: str, output_path: str, key: bytes) -> None:
"""
Decrypt a file using the given Fernet key.
- input_path: path to the encrypted file
- output_path: path where the decrypted file will be written
- key: bytes key used for encryption
"""
f = Fernet(key)
with open(input_path, "rb") as file:
encrypted_data = file.read()
decrypted_data = f.decrypt(encrypted_data)
with open(output_path, "wb") as file:
file.write(decrypted_data)
if __name__ == "__main__":
# Example usage:
# 1) Generate and save a key (do this once and reuse the same key to decrypt later)
key_file = "secret.key"
key = generate_key(key_file) # or: key = load_key(key_file) if already generated
# 2) Encrypt a file
encrypt_file("example.txt", "example.txt.enc", key)
# 3) Decrypt the file
decrypt_file("example.txt.enc", "example_decrypted.txt", key)
Important:
- Keep
secret.key safe; anyone with this key can decrypt your data.
- To decrypt later or on another machine, load the same key with
load_key("secret.key").