Create your own file encrypter in python

file encryption in python

In the 21st Century, data security is the main concern for everyone for keeping their files safe so that no one can see even if there is a data leak from your computer. In this post I will explain how you can create your own file encrypter in python with in 5 minutes.

Are you using a third party or free software for securing your data on your computer? If yes then you will be shocked to know that most of the software only restricts the permissions on the folders. They do not encrypt them. Anyone can see your data if your device is stolen by attaching your hard drive to another computer. So how it happens?

You or anyone else can modify the permissions of the folders easily by using software like NTFSAccess for windows. After modifying the permissions anyone can take ownership of your files and use them however they want.

Python is a great programming language for creating small utilities in minutes. Follow this post to create your own file encrypter and decrypter easily.

What is Encryption

Encryption is a process for converting your files in a way that no one can understand what the file is and what inside it. The purpose of this process is to prevent unauthorized access to those files. Only the owner can view those files by decrypting them with the key which is used to encrypt.

Requirements

  • Python installed on your machine.
  • Little programming knowledge

Create your own file encrypter and decrypter

In python, it is very easy to create such a small utility by using the AES encryption algorithm.

Step 1 – Install python on your machine. After installing open command prompt and enter python -V command to check if it is installed. If you cant find python command error then add the python installation directory to your environment variables.

Search on google “how to add python to environment variables” if you are not able to do it.

Step 2 – Optionally you can create a virtual environment to not disturb the main python package. But it’s ok to go with the main python as it will give us a shortcut way to encrypt and decrypt files.

Step 3 – Install the following library using pip install command.

pip install pyaescrypt==0.4.3

The Code

Step 4 – Create a text file name it “lockmyfiles.py“. The extension .py is important. Paste the following code into it and save.

import time

import pyAesCrypt
from os import stat, remove
import sys
import os

path = "."
bufferSize = 64 * 3 * 1024
ACTION_ENCRYPT = 'encrypt'
ACTION_DECRYPT = 'decrypt'
encrypted_file_extenstion = ".aes"


def get_normal_file_name(encrypted_filename):
    return encrypted_filename.replace(encrypted_file_extenstion, '')


def get_encrypted_file_name(normal_filename):
    return normal_filename + encrypted_file_extenstion


def encrypt_files_in_folder(action=ACTION_DECRYPT):
    for root, d_names, f_names in os.walk(path):
        for f in f_names:
            real_file_path = os.path.join(root, f)
            print("Processing " + str(real_file_path))
            if action == ACTION_ENCRYPT:
                encrypt(real_file_path)
            else:
                decrypt(real_file_path)


def check_if_encrypted(filename):
    if encrypted_file_extenstion in filename:
        return True
    else:
        return False


def encrypt(normal_filename):
    if check_if_encrypted(normal_filename):
        print("File is already encrypted")
        return
    # encrypt
    with open(normal_filename, "rb") as fIn:
        with open(get_encrypted_file_name(normal_filename), "wb") as fOut:
            pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize)
    remove(normal_filename)


def decrypt(encrypted_filename):
    if not check_if_encrypted(encrypted_filename):
        print("File is not Encrypted")
        return
    # get encrypted file size
    encFileSize = stat(encrypted_filename).st_size
    error = False
    # decrypt
    with open(encrypted_filename, "rb") as fIn:
        try:
            with open(get_normal_file_name(encrypted_filename), "wb") as fOut:
                # decrypt file stream
                pyAesCrypt.decryptStream(fIn, fOut, password, bufferSize, encFileSize)
        except ValueError as e:
            # remove output file on error
            print(e)
            error = True
    if not error:
        os.remove(encrypted_filename)
    else:
        remove(get_normal_file_name(encrypted_filename))


if __name__ == '__main__':
    start_time = time.time()
    action = input("Enter Action, 1 for encrypt 2 for decrypt\n")
    if int(action) == 1:
        ACTION = ACTION_ENCRYPT
    elif int(action) == 2:
        ACTION = ACTION_DECRYPT
    else:
        ACTION = None
        print("Invalid Action")
        sys.exit()
    print("Action Accepted")
    password = input("Enter New password for encryption and old password for decryption\n")
    encrypt_files_in_folder(ACTION)
    print(str(time.time() - start_time) + " Seconds elapsed")

Step 5 – Now put this file into “C:\Windows\system32” folder. By putting it in system 32 folder you will be able to call this script quickly by opening command prompt from the navigation bar. Otherwise, you will have to call the script manually by navigating the script in command prompt.

Step 6 – The encryption and decryption code is ready now its time to test it. If you have not added that file to the system32 folder then open the command prompt and navigate to a folder which has some files.

Step 7 – Navigate to the folder where you want to encrypt the files. Click on the navigation bar and type lockmyfiles.py. Then hit enter. “lockmyfiles.py” is the file name from step 4.

create your own file encrypter in python

You will see something like “enter your action”. See the image below.

Enter you action, 1 – For encryption and 2 for decryption.

After entering the action enter the password, New password for encryption, and existing password for decryption.

file encryption enter action

After that you will see the process of encryption and decryption.

encryption decryption success

Please note that this program will encrypt all files within a folder and also the files in all of its subfolders recursively.

Also, note that You will need to keep the encryption password safe. There will be no way to recover the password if you forget after encrypting the files.

Related posts

One Thought to “Create your own file encrypter in python”

  1. Hibbett Sports Locations

    Hello. This post was extremely interesting, particularly because I was looking
    for thoughts on this subject last Thursday.
    Best regards,
    Thomassen Henneberg

Leave a Comment