• Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
  • Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
Home Guides Programming Python

Encrypt and Decrypt Files with Python

Jonathan Moore by Jonathan Moore
4 years ago
Reading Time: 6 mins read
A A
Encrypt and Decrypt Files with Python
FacebookTwitter

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.

Plain Data

Encryption is a means of securing digital data using one or more mathematical techniques, along with a password or "key" used to decrypt the information. The encryption process translates information using an algorithm that makes the original information unreadable. The process, for instance, can convert an original text, known as plaintext, into an alternative form known as ciphertext. When an authorized user needs to read the data, they may decrypt the data using a binary key. This will convert ciphertext back to plaintext so that the authorized user can access the original information.

Encrypted Data

gAAAAABhL8AgZ-Hvaw-uLNxyBM7Fk1GJvbtVzII1GHsbG8R7bXW4W6Fbj_RPccgrYqvhnUzBuIqzgxwTgBIIGoSuV6BsRxbQDmICjkGnPx1yFeYIwDQGQnU1AOW_0NRC7TYW_A7IA3ljjpT2_xEUFfVgszYirOi59dQ3o-O-AZOexEGGLtE_EmvcOGuRJCt3lx7E_ZIXYl4UfhAKflX9ubLothEm3OHF_L39V02gpz8dv3jgP_zrnQrsmnORtR5XtgybOZjZ1BZaqQCBSO66umOtBjzlqf6qtPEJn3bSVtsdTYR-1hxvnyrWC1FpDdhZah30YPcL3rHdBm9dJEYhqJSzmNzguXIBiDzy34l6KZHSYhX2LhFCJH4YqXqSnichOOl5gf-AN1KL4sM4aobRGFK845YZiCZoT2PBS5ijBSsf9UWUSTViYOYv2cnQ3WAAv_j8wYxYtDCTvUbBl_onbo8WLLzxJE-QbZokYkr5G2AKqJIL5Eo9hF1iQQJqyAi5hoFe9_F-FaRUL3OZ2hO8xLSsM3Me7aerPf7cyjM3Iz5oZAY9hU7-uhx00DiyaFYcemQtEDeakcjqrN0jgC4RjiS53_KMqrl7si__KJjDnklw4o6BZDWZdguaIOpSBwmD8EJc5oZQY14zMlj4oj21WtYiGjuHjcZk8RTc5jygObabPki9LWsfIg1nNLNLA-NtzbxZwzPbyVZIlfXZtgDnV-p9sfGkSmiz9Artbd3GJ_P8yRr9VriAdVXI9Vab9ajxlBFEvjFQFN-r_zSz_cRh-6OGbqca1HoCqBdFbrhnXfmf9hDUh0VI0YVjBAE6iA=

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<br>
    |___ generate_key.py<br>
    |___ encryptor.py<br>
    |___ decryptor.py<br>
    |___ private.key (auto-created)<br>
    |___ vault<br>
          |___ TestFile1.jpg<br>
          |___ TestFile2.mp3<br>
          |___ TestFile3.mp4<br>
          |___ TestFile4.pdf<br>
          |___ TestFile5.txt<br>
          |___ TestFile6.docx<br>
          |___ TestFile7.xlsx<br>
          |___ TestFile8.zip<br>

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.

Note: You need to keep this key in a safe place. If you lose the key, you won't be able to decrypt the data that was encrypted with this key.

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.

Tags: CryptographyDecryptionEncryptionPrivacyPythonSecurity
ShareTweetSharePinShareShareScan
ADVERTISEMENT
Jonathan Moore

Jonathan Moore

Senior Software Engineer and Cybersecurity Specialist with over 3 decades of experience in developing web, desktop, and server applications for Linux and Windows-based operating systems. Worked on numerous projects, including automation, artificial intelligence, data analysis, application programming interfaces, intrusion detection systems, streaming audio servers, WordPress plugins, and much more.

Related Articles

Why Stable Websites Outperform Flashy Redesigns

Why Stable Websites Outperform Flashy Redesigns

Most websites do not fail in dramatic fashion. There is no explosion, no warning siren, no obvious moment where everything...

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Building a Network Tracker Auditor for Privacy with Python

Building a Network Tracker Auditor for Privacy with Python

In my last post, I dug into AdGuard, a robust ad blocker that tackles trackers and ads head-on. But how...

Next Post
Add a Google Map to Your Website

Add a Google Map to Your Website

Recommended Services

Latest Articles

Building a Simple WordPress Post List Tool with PHP

Building a Simple WordPress Post List Tool with PHP

I needed a quick way to view all my WordPress posts without logging into the admin dashboard. Sometimes you just...

Read moreDetails

Why Stable Websites Outperform Flashy Redesigns

Why Stable Websites Outperform Flashy Redesigns

Most websites do not fail in dramatic fashion. There is no explosion, no warning siren, no obvious moment where everything...

Read moreDetails

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Read moreDetails

My SSH Setup: How I Manage Multiple Servers

My SSH Setup: How I Manage Multiple Servers

If you work with more than one server, the need to manage multiple servers with SSH becomes obvious pretty quickly....

Read moreDetails
  • Privacy Policy
  • Terms of Service

© 2025 JMooreWV. All rights reserved.

No Result
View All Result
  • Home
  • Guides
    • Linux
    • Programming
      • JavaScript
      • PHP
      • Python
    • Tools
    • WordPress
  • Blog
    • Artificial Intelligence
    • Tutorials
    • Privacy
    • Security
  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity