Python3

Python script: File Encryption Tool (using symmetric-key cryptography)


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(filename, key):
fernet = Fernet(key)
with open(filename, "rb") as file:
file_data = file.read()
encrypted_data = fernet.encrypt(file_data)
with open(filename, "wb") as file:
file.write(encrypted_data)

def decrypt_file(filename, key):
fernet = Fernet(key)
with open(filename, "rb") as file:
encrypted_data = file.read()
decrypted_data = fernet.decrypt(encrypted_data)
with open(filename, "wb") as file:
file.write(decrypted_data)

# Usage example
generate_key()
key = load_key()
encrypt_file("example.txt", key)
decrypt_file("example.txt", key)

In this Python script, we have implemented a simple file encryption tool using symmetric-key cryptography. We are using the Fernet symmetric encryption algorithm provided by the cryptography library.

Here’s a brief explanation of the functions in the script:
1. `generate_key()`: This function generates a random encryption key and saves it to a file named “key.key”.
2. `load_key()`: This function loads the encryption key from the “key.key” file.
3. `encrypt_file(filename, key)`: This function encrypts the contents of the specified file using the provided encryption key.
4. `decrypt_file(filename, key)`: This function decrypts the contents of the specified file using the provided encryption key.

At the end of the script, there is an example of how to use these functions to encrypt and decrypt a file named “example.txt”.

This script can be expanded upon by adding error handling, input validation, and user prompts to enter file names and interactively use the tool.