In this guide, I will be showing you how to encrypt and decrypt a directory of files by using the Cryptography library for Python.
Encryption is the process of transforming data into a form called “ciphertext,” which conceals the data's original information to prevent it from being known or use. If the transformation is reversible, the corresponding reversal process is called “decryption,” which is a transformation that restores encrypted data to its original state.
We will be using Symmetric Encryption for this application, which uses the same generated private key for both encryption and decryption of the file data. I will also be introducing you to a new Python library called Cryptography. This will allow us to utilize a strong 128-bit AES algorithm for our encryption process. The data that we encrypt cannot be manipulated or read without the private key generated.
This encryption and decryption project has been tested with image files, MP3 files, MP4 files, PDF files, ZIP files, and document files without losing data. It is highly recommended that you test this on copies of files and not on the original files until you are sure it works correctly.
Our Requirements
Before we get started, you will need to install the Cryptography library for Python. The Cryptography library includes high-level recipes and low-level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests, and key derivation functions.
pip install cryptography
Let’s Get Started
This project will consist of 3 standalone scripts, which means each can be executed independently without requiring the other. Although you can combine the 3 into one, I separated them for both comprehension and safety. I didn't want you to encrypt files that you didn't want to encrypt accidentally, nor did I want you to risk generating a new private key between the encryption and decryption process and be unable to regain the use of your files.
Create a project directory that will contain the following 3 scripts. Within that project directory, create a subdirectory called vault. Your project directory should look similar to this:
Your Project Directory
|___ generate_key.py
|___ encryptor.py
|___ decryptor.py
|___ private.key (auto-created)
|___ vault
|___ TestFile1.jpg
|___ TestFile2.mp3
|___ TestFile3.mp4
|___ TestFile4.pdf
|___ TestFile5.txt
|___ TestFile6.docx
|___ TestFile7.xlsx
|___ TestFile8.zip
We will be placing the files that we want to encrypt into the vault subdirectory. This is to help prevent us from encrypting important files in a directory that might be essential to our operating system or files that we cannot afford to lose if something goes wrong. Place a few test files within the vault subdirectory. You can also create a tree of subdirectories within the vault subdirectory to place test files.
Create a file called generate_key.py and insert the following code into it:
#!/usr/bin/python3 from cryptography.fernet import Fernet def create_key(key_name): """ Generates a private key and saves it into a file """ # Call the 'generate_key' function within the Fernet class. private_key = Fernet.generate_key() # Create a file named 'private.key'. with open(key_name, "wb") as key_file: # Write the generated key to the new file. key_file.write(private_key) if __name__ == "__main__": # Call the 'create_key' function and pass a name for the # key file. We are using 'private.key' as the file name. # If you change the file name, be sure to change it in # the 'encryptor.py' and 'decryptor.py' files as well. create_key("private.key")
This is a short script that will create a file called private.key. This should only be executed when you have no encrypted files that need to be decrypted. If you run this while there are encrypted files, you will not be able to decrypt those files again since you will not have the correct key to decrypt them with.
Now create a file called encryptor.py and insert the following code into it:
#!/usr/bin/python3 import os from cryptography.fernet import Fernet """ WARNING: Make sure you are encrypting the correct directory, otherwise you may end up encrypting files that might be essential to the operation of your system. Check and double-check the directory location before running this script. """ class Encryptor: def load_key(self, key_name): """ Loads the private key from the current directory. """ try: private_key = open(key_name, "rb").read() except FileNotFoundError: exit("Unable to locate the " + key_name + " file.") return private_key def encrypt_files(self, path, private_key): """ Walkthrough directory and encrypt all files not ending with '.aes' """ # Iterate through all files in directory and subdirectories. for path, sub_dirs, files in os.walk(path): # Iterate through found files in the directory. for file in files: # Join the file with the original directory to create the path. file_path = os.path.join(path, file) # If the file already ends with '.aes' ignore and continue. if file_path.lower().endswith(".aes"): continue # If the file doesn't end with '.aes' the encrypt file. self.encrypt_file(file_path, private_key) def encrypt_file(self, file, private_key): """ Open file, encrypt contents, and save as a new encrypted file. """ # Initialize the Fernet class f = Fernet(private_key) # Read original file data, encrypt data, and store in a variable. encrypted = f.encrypt(open(file, "rb").read()) # Create a new file and add '.aes' to the file name. with open(file + ".aes", "wb") as encrypted_file: # Write encrypted data to the new file. encrypted_file.write(encrypted) # Delete the original file. os.remove(file) if __name__ == "__main__": # Initialize the Encryptor class encryptor = Encryptor() # Load the private key named `private.key` from the current directory. private_key = encryptor.load_key("private.key") # Call 'encrypt_files' function within the Encryptor class while # passing the vault directory that is within the current directory # to find files to encrypt. encryptor.encrypt_files("vault", private_key)
The encryptor script will traverse through the vault subdirectory and its subdirectories to look for any file that doesn't end with .aes. When a file needs to be encrypted, it will use the private key from the private.key file to encrypt the contents within that file and store it into temporary memory. The encrypted data will then be transferred from memory and written to a new file with .aes appended to the filename. The original file is then deleted from the directory.
Let's create our last file called decryptor.py and insert the following code into it:
#!/usr/bin/python3 import os from cryptography.fernet import Fernet, InvalidToken class Decryptor: def load_key(self, key_name): """ Loads the private key from the current directory. """ try: private_key = open(key_name, "rb").read() except FileNotFoundError: exit("Unable to locate the " + key_name + " file.") return private_key def decrypt_files(self, path, private_key): """ Walkthrough directory and decrypt all files ending with '.aes' """ # Iterate through all files in directory and subdirectories. for path, sub_dirs, files in os.walk(path): # Iterate through found files in the directory. for file in files: # Join the file with the original directory to create the path. file_path = os.path.join(path, file) # If the file ends with '.aes' then decrypt the file. if file_path.lower().endswith(".aes"): self.decrypt_file(file_path, private_key) def decrypt_file(self, file, private_key): """ Open an encrypted file, decrypt contents, and save it as the original file. """ # Initialize the Fernet class f = Fernet(private_key) try: # Read encrypted file data, decrypt data, and store in a variable. decrypted = f.decrypt(open(file, "rb").read()) # Create a new file and remove '.aes' from the file name. with open(file.replace(".aes", ""), "wb") as decrypted_file: # Write decrypted data to the new file. decrypted_file.write(decrypted) # Delete the encrypted file. os.remove(file) except InvalidToken: # The private key does not match the key that the file was # encrypted with. exit("Unable to decrypt the files. The private key is invalid.") if __name__ == "__main__": # Initialize the Decryptor class decryptor = Decryptor() # Load the private key named `private.key` from the current directory. private_key = decryptor.load_key("private.key") # Call 'decrypt_files' function within the Decryptor class while # passing the vault directory that is within the current directory # to find files to decrypt. decryptor.decrypt_files("vault", private_key)
The decryptor script also traverses through the vault subdirectory and its subdirectories to look for any file that ends with .aes. When a file is found to be encrypted, it will use the private key from the private.key file to decrypt the contents within the file and store it into temporary memory. The decrypted data will then be transferred from memory and written to a new file without the .aes extension appended to the filename. The encrypted file is then deleted from the directory.
Recommendations
I recommend making a backup copy of the private.key file after you generate it and place it in a safe location. As mentioned previously, without this key, you will not be able to decrypt your encrypted files. I also recommend moving the generate_key.py file to a different location so you don't accidentally rerun it after encrypting your files. Another option is to have the generate_key.py file check to see any encrypted files exist and prevent the script from running if they do exist (refer to the encrypt_files function within the Encryptor class).
Conclusion
This is a fun project to play around with. There are many possibilities that you can do with this by expanding its codebase to include more advanced features. You can create your own encrypted vault to prevent others from viewing your important and private files. Perhaps even store the private key on a different device and make that device required to decrypt the files.