Hey! What’s up students? Welcome back. In my previous article I mentioned that I’m going to teach you how to create a file encryption and decryption tool using python. So this tutorial is going to be it. Before proceeding further in this tutorials make sure to read this article. That article contains the basics required when we building this file encryption and decryption tool. So without further ado let’s get into the tutorial.
What is a file encryption and decryption?
Basically a file encryption and decryption tool is a piece of software or a script written to perform encryption and decryption. For example, let’s say you have a text file with all your social media credentials saved on it. If anyone opens the file he/she can easily steal your credentials. Because your credentials are stored in plain text within that text file. By using a file encryption and decryption tool you can simply encrypt the content within the file. So that if anyone else access this file without your permission they cannot steal your credentials.
So there are many file encryption and decryption tool out there. Some of them are open source and some of them are paid software. Today we are going to learn how to create a file encryption and decryption tool using python programming language.
Building the structure of our file encryption and decryption tool.
So here’s how we going to make this tool. We are going to use AES encryption method in this tool.
When user execute this tool it should ask the user the following options.
- Encrypt a File
- Decrypt a File
If user select the option 1;
- First we need to ask for an encryption key to use during the encryption.
- Then we need to ask for the file name that they need to encrypt.
- During the encryption process
- We need to add padding to the data.
- Generate a strong key based on the encryption key entered by user.
- Generate IV
- Adding Salt to strengthen the password
- Perform encryption.
- During Encryption we need to store the key and IV within the encrypting file. So that we can extract the key and IV during decryption.
- Encode with base64
If user select the option 2;
- First we need to ask for the file name that they need to decrypt.
- Then we have to ask for the encryption key that they have used during the encryption of that file.
- During this process without going further we need to check for the validity of this key by reading the stored key in the encrypted file.
- If the key is valid we can perform the decryption of that file.
- If the key is not valid we can terminate the process.
If user select the option 3;
- We can ask are they sure about the selection.
- If yes > Exit the Program.
- If No > Reload the Program.
Let’s make this happen…
First of all we need few libraries. They are,
Now we can import these libraries into our python script. By the way os, sys and base64 are inbuilt python libraries. Therefore, you don’t have to install them. But funcy and pycryptodome are not inbuilt therefore you have to install them. Since we don’t need each and every module inside pycryptodome library first of all we need import the modules that we need.
import os import sys import funcy import base64 import Crypto.Protocol from Crypto import Random from Crypto.Cipher import AES
Now let’s create a function to quite the program when user select the option 3.
def quit(): alpha = input("Are You Sure?[yes/no] - ").lower() if alpha == "yes": exit() if alpha == "no": choice() #Don't worry about this you'll get this in latter steps
Now let’s define some variable.
usr_key = input("Please enter a key to use as your encryption key:- ") salt = b'\x9aX\x10\xa6^\x1fUVu\xc0\xa2\xc8\xff\xceOV' key = Crypto.Protocol.KDF.PBKDF2(password=usr_key, salt=salt, dkLen=32, count=10000) iv = Random.new().read(AES.block_size) bs = AES.block_size
usr_key variable will ask for the encryption key. salt is a random string that i used. you can use any value here. key variable will generate a strong key using the encryption key and salt with help of PBKDF2 protocol. iv variable will generate a random Initialization Vector. bs variable define the block size.
Now let’s create the padding function for use during encryption process.
def pad(s): return s + (bs - len(s) % bs) * chr(bs - len(s) % bs).encode('utf-8')
def encrypt(raw): raw = pad(raw.encode("utf-8")) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(key + iv + cipher.encrypt(raw))
Now let’s create a function to implement the above created functions to encrypt out files.
def encryptFile(fileIn, chunksize=64*1024): fileOut = fileIn + ".cursed" cipher = AES.new(key, AES.MODE_CBC, iv) with open(fileIn, "rb") as plain: with open(fileOut, "wb") as outFile: outFile.write(base64.b64encode(key + iv)) while True: chunk = plain.read(chunksize) if len(chunk) == 0: break chunk = pad(chunk) outFile.write(base64.b64encode(cipher.encrypt(chunk))) os.remove(fileIn) encryptFile(input("Enter name of the file to encrypt:- "))
In the above function we take the file mentioned by the user append “.cursed” to the end of the file name extention. then we read the data in binary, encrypt them and write the encrypted data into the file together with the key and iv. By the way these encrypted data are written to the file as base64 encoded strings. And also we are encrypting these in chunks. Finally we we delete the original file.
Here comes the decryption process.
def unpad(s): return s[:-ord(s[len(s) - 1:])] def decrypt(l): l = base64.b64decode(l) alpha = l[:32] key == alpha iv = l[32:32 + 16] cipher = AES.new(key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(l[48:])) def decryptFile(fileIn, chunksize=24*1024): with open(fileIn, "rb") as encryptedFile: encrypted = base64.b64decode(encryptedFile.read(64)) setup = encrypted[:48] key_confirm = input("Please enter the key used to encrypt the file:- ") salt = b'\x9aX\x10\xa6^\x1fUVu\xc0\xa2\xc8\xff\xceOV' key_check = Crypto.Protocol.KDF.PBKDF2(password=key_confirm, salt=salt, dkLen=32, count=10000) if key_check == setup[:32]: print("Password Correct!") else: print("Wrong Password!") sys.exit(0) iv = setup[32:] cipher = AES.new(key_check, AES.MODE_CBC, iv) with open(fileIn[:-7], "wb") as decryptedFile: encrypted = base64.b64decode(encryptedFile.read()) chunks = list(funcy.chunks(chunksize, encrypted)) for chunk in chunks: decrypted_chunk = unpad(cipher.decrypt(chunk)) decryptedFile.write(decrypted_chunk) decryptFile(input("Enter name of the file to decrypt:- "))
First function will remove all padding. second function will do the decryption. last function will apply these to the file and give us the clear text file back. Last function will check the validity of encryption key.
You can get the complete code by visiting the below link.
Keep Visiting this site frequently so that you will never miss a post. Thank you.