Secure Your Folders: Encrypt & Decrypt in Python with AES

Boy holding locked folder with Python logo, key to unlock it. Learn to encrypt & Decrypt folders with Python.

Introduction

If you’re a computer user, you likely have a treasure trove of documents, photos, and other files scattered across various folders. However, within that collection, there might be sensitive files that need to be stored safely. For example, your credit card information, a government ID proof, or just some private media files.

Encryption is a great way to protect that information. But can you think of encrypting every individual file one by one? It would be a tedious task. What if we encrypt an entire folder containing any files? It would be a super easy task, right?

In this lesson, you will learn how to encrypt and decrypt a folder using the AES-256 encryption in Python. AES (Advanced Encryption Standard) is a powerful algorithm used by governments and security experts alike. We will use a 256-bit key for encryption and this key will must be required for decryption. It will add extra strength to our encryption process.

So, let’s dive into the folder and secure it.

What is the AES Algorithm?

The Advanced Encryption Standard (AES) is a widely adopted symmetric-key encryption algorithm established by the National Institute of Standards and Technology (NIST) in 2001. It’s considered one of the most secure block ciphers, meaning it encrypts data in fixed-size blocks.

AES-256 is a specific variant of AES that uses a 256-bit key length that offers a very high level of encryption strength.

Why Encrypt a Folder?

Imagine carrying a briefcase filled with confidential documents. Encryption acts as a virtual lock on your digital briefcase. It ensures that only authorized individuals can access its contents.

For example, If your computer is stolen or someone gains access to your storage, your encrypted files remain unreadable without the decryption key. So, your sensitive information, like financial documents or personal photos, is encrypted offers a sense of security.

Requirements

To run the programs, you’ll need Python 3 and the pyzipper library installed. You can install it using pip:

pip install pyzipper

Encrypt a Folder

Now, let’s encrypt a folder using Python!

import os
import pyzipper
def encrypt_folder(input_folder, output_file, password):
    with pyzipper.AESZipFile(output_file, 'w', compression=pyzipper.ZIP_LZMA) as zf:
        zf.setpassword(password.encode('utf-8'))
        zf.setencryption(pyzipper.WZ_AES, nbits=256)
        
        for foldername, subfolders, filenames in os.walk(input_folder):
            for filename in filenames:
                file_path = os.path.join(foldername, filename)
                arcname = os.path.relpath(file_path, input_folder)
                zf.write(file_path, arcname=arcname)
if __name__ == "__main__":
    input_folder = 'Folder_Path'
    output_file = 'encrypted_folder.zip'
    # Password must be 32 bytes (256-bit) long
    password = 'Your_Password_Here'
    encrypt_folder(input_folder, output_file, password)
    print(f"Folder '{input_folder}' has been encrypted as '{output_file}'")

Steps

  1. Create a new Python file (e.g., encrypt_folder.py) using your favorite code editor.
  2. Copy and paste the following code into the file.
  3. Replace the placeholders with your desired values:
    • input_folder: Path to the folder you want to encrypt.
    • output_file: Path and name for the encrypted zip file (e.g., encrypted_folder.zip).
    • password: 32 bytes (256-bit) long encryption password (You can use this sample password for a demo: ‘OcIuSk8dGjHEzNYtmo4pqZDQBFsP3rlU’).

Explanation of the Program

  • The encrypt_folder function takes three arguments: the folder path, the output filename for the encrypted zip file, and the password (converted to bytes for security).
  • with pyzipper.AESZipFile(output_file, 'w', compression=pyzipper.ZIP_LZMA) as zf: This line opens a new zip file for writing ('w') using the AESZipFile class and assigns it to the variable zf. The compression method is set to LZMA (compression=pyzipper.ZIP_LZMA) for space efficiency.
    • zf.setpassword(password.encode('utf-8')): This line sets the password for the zip file. The password is converted to bytes using encode('utf-8') for security reasons, as encryption algorithms typically work with byte data.
    • zf.setencryption(pyzipper.WZ_AES, nbits=256) (Optional): This line explicitly sets the encryption method to AES with a key size of 256 bits. While some implementations might set this by default with AESZipFile, including it ensures clarity.
  • for foldername, subfolders, filenames in os.walk(input_folder): This loop iterates through the entire directory structure of the input_folder using os.walk.
    • foldername: This holds the current folder name within the hierarchy.
    • subfolders: This is a list of subfolder names within the current folder.
    • filenames: This is a list of filenames within the current folder.
  • for filename in filenames: This inner loop iterates through each filename within the current folder.
    • file_path = os.path.join(foldername, filename): This line constructs the complete file path by joining the foldername and filename using os.path.join.
    • arcname = os.path.relpath(file_path, input_folder): This line calculates the relative path of the file within the zip archive using os.path.relpath. This ensures the files are stored with an organized structure inside the zip file.
    • zf.write(file_path, arcname=arcname): This line adds the file from the file_path to the zip archive using the calculated arcname as its internal path within the zip.

Output

Once you run the script, you’ll see a confirmation message indicating that your folder has been encrypted and saved as the specified zip file. This encrypted zip file can now be securely stored or transferred, and its contents remain inaccessible without the decryption password.

Decrypt the Encrypted Zip File

Having an encrypted folder is great for security, but you’ll also need a way to access the files later. Here’s a Python program to decrypt the zip file you created:

The Program

import pyzipper

def decrypt_zip(input_file, output_folder, password):
    with pyzipper.AESZipFile(input_file) as zf:
        zf.setpassword(password.encode('utf-8'))
        zf.extractall(path=output_folder)

if __name__ == "__main__":
    input_file = 'encrypted.zip'
    output_folder = 'decrypted_folder'
    password = 'Your_Password_Here'

    decrypt_zip(input_file, output_folder, password)
    print(f"{input_file} has been decrypted into folder '{output_folder}'")

Explanation

  • The decrypt_zip function takes the encrypted zip file path, the desired output folder path, and the password (in bytes) as arguments.
  • It opens the zip file using pyzipper.AESZipFile.
  • The password is set using zf.setpassword.
  • The zf.extractall method extracts all files from the zip archive to the specified output_folder.
  • A confirmation message is printed upon successful decryption.

Output

Running this program will extract the decrypted files from the zip archive into the designated output folder. You’ll then be able to access the original files within that folder.

Summary

In this article, we learned how to encrypt and decrypt an entire folder in Python using the powerful AES-256 Encryption. The folder might contain any type of files. To perform this task, we used Python’s pyzipper library and OS module. The encryption program traces all the files under the given folder hierarchy and compresses them into zip format. Then it encrypts the zip file using the AES algorithm and sets a 256-bit strong key. Decryption, of course, will require the same key.

Encrypting an entire folder might prove a very useful thing for our practical use. You can safely store your private documents, data, and media on your computer or sending online, just by encrypting them. The AES-256 encryption ensures that it is almost impossible to decrypt the data without having the secret key.

If interested, explore more information on the AES algorithm and its various usage from the following articles:

So, what do you think? Share your thoughts in the comments below. I would love to hear from you.

Happy Coding!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 147

Leave a Reply

Your email address will not be published. Required fields are marked *