create a file encryption script in python

To create a file encryption script in Python, the steps are:

  1. Import the required modules
  2. Define the encryption function
  3. Define the decryption function
  4. Test the functions

Here is the sample code:

main.py
import os
from cryptography.fernet import Fernet

#Generate a key for encryption
def generate_key():
    key=Fernet.generate_key()
    with open("secret.key","wb") as key_file:
        key_file.write(key)

#Load the previously generated key file
def load_key():
    return open("secret.key","rb").read()

#Encrypt the file
def encrypt_file(filename, key):
    f=Fernet(key)
    with open(filename,"rb") as file:
        file_data = file.read()
    encrypted_data = f.encrypt(file_data)
    with open(filename,"wb") as file:
        file.write(encrypted_data)

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

#Test the functions
generate_key()
key=load_key()
encrypt_file("test.txt", key)
decrypt_file("test.txt", key)
935 chars
37 lines

In this code, we are using the cryptography module for encryption, which provides strong encryption algorithms. The generate_key() function generates a random secret key and writes it to a file. The load_key() function reads the secret key from the file. The encrypt_file() function accepts a filename and a secret key as inputs, reads the content of the file, encrypts it using the secret key, and writes the encrypted content back to the file. The decrypt_file() function does the reverse, reads the encrypted content from the file, decrypts it using the secret key, and writes the decrypted content back to the file.

To use this script to encrypt a file, simply call encrypt_file(filename, key) with the name of the file you want to encrypt and the secret key. To decrypt the file, call decrypt_file(filename, key) with the same filename and secret key.

Note that you should keep the secret key secure, as losing it will prevent you from decrypting the encrypted files.

related categories

gistlibby LogSnag