File Encryption And Decryption Using Python

File Encryption Decryption

Encryption is considered one component of a successful security strategy.

Successful encryption completely depends on robust passwords and passphrases called “keys”.

Why Encryption is important?

  • For maintaining the security of financial and other R&D data with various internal data which needs to be safe from intruders.
  • The employees or organizations do not want their financial or private items to be made public.
  • To make quick transitions so that private items are not made public.

Encryption scrambles text to make it unreadable by anyone other than those with the keys to decode it, and it’s becoming less of an added option and more of a must-have element in any security strategy for its ability to slow down and even deter hackers from stealing sensitive information.

If good encryption is capable of hindering investigations by FBI experts, consider what it could do for you and your company’s sensitive information.

Before understanding the use of Python programming language, you can read Why is Python Programming Language So Popular Among Programmers? for understanding its importance and other essential facts. And if you are not sure about the right IDE or Editor to use for Python programming, then you can read Best IDEs and Code Editors for Python Developer- 2019.

Read More: Jobs In Demand For 2020 & Beyond: 15 Careers You Can’t Ignore!!

PyCrypto Module:

PyCrypto is the collection of secure hash functions and various encryption algorithms.

The package is designed in such a way to make structured modules as and when required. With Python we can encrypt and decrypt the files as and when required.

“PyCrypto” needs to be installed in your local system to follow the procedure of encryption and decryption of files before the transmitting in a specified channel.

The installation command for this module is:

pip install pycrypto


PyCrypto Package Installation:

Collecting pycrypto


Collecting shellescape (from Crypto)


Collecting Naked (from Crypto)

Downloading (590kB)

100% |████████████████████████████████| 593kB 771kB/s

Collecting requests (from Naked->Crypto)

Using cached

Collecting pyyaml (from Naked->Crypto)

Cache entry deserialization failed, entry ignored

Downloading (188kB)

100% |████████████████████████████████| 194kB 426kB/s

Collecting urllib3<1.24,>=1.21.1 (from requests->Naked->Crypto)

Using cached

Collecting idna<2.8,>=2.5 (from requests->Naked->Crypto)

Using cached

Collecting chardet<3.1.0,>=3.0.2 (from requests->Naked->Crypto)

Using cached

Collecting certifi>=2017.4.17 (from requests->Naked->Crypto)

Downloading (147kB)

100% |████████████████████████████████| 153kB 473kB/s

Installing collected packages: shellescape, urllib3, idna, chardet, certifi, requests, pyyaml, Naked, Crypto

Successfully installed Crypto-1.4.1 Naked-0.1.31 certifi-2018.8.24 chardet-3.0.4 idna-2.7 pyyaml-3.13 requests-2.19.1 shellescape-3.4.1 urllib3-1.23

Algorithm for file encryption:

1. Python accepts the file input and encrypts it using the Pycrypto module.
2. The filename is taken as input parameter along with the password.
3. Encryption is achieved with the help of key which is generated with SHA-256 algorithmic standards. The encrypted file is saved in the same directory with a prefix of (encrypted) added to it.
4. SHA-256 cryptographic hash function generates keys which helps in maintaining security of files that are used for symmetric encryption of files.
5. The files are basically protected with passwords.
6. Decryption follows the reverse procedure where the password and encrypted file is taken input parameters.

The code for file encryption and decryption is mentioned below:

import os
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random

#Encryption of files
def encrypt(key, filename):
chunksize =
64 * 1024
outputFile = “(encrypted)” + filename
filesize = str(os.path.getsize(filename)).zfill(
IV =

encryptor =, AES.MODE_CBC, IV)

with open(filename, ‘rb’) as infile:
with open(outputFile, ‘wb’) as outfile:

while True:
chunk =

if len(chunk) == 0:
len(chunk) % 16 != 0:
chunk +=
b’ ‘ * (16 – (len(chunk) % 16))


#Decryption of files
def decrypt(key, filename):
chunksize =
64 * 1024
outputFile = filename[11:]

with open(filename, ‘rb’) as infile:
filesize = int(
IV =

decryptor =, AES.MODE_CBC, IV)

with open(outputFile, ‘wb’) as outfile:
while True:
chunk =

if len(chunk) == 0:


def getKey(password):
hasher =
return hasher.digest()

def Main():
choice = input(
“Would you like to (E)ncrypt or (D)ecrypt?: “)
if choice == ‘E’ or choice == ‘e’:
filename = input(
“File to encrypt: “)
password = input(
“Password: “)
, filename)
elif choice == ‘D’ or choice == ‘d’:
filename = input(
“File to decrypt: “)
password = input(
“Password: “)
, filename)
print(“No Option selected, closing…”)

if __name__ == ‘__main__’:

Output for Encryption:


Would you like to (E)ncrypt or (D)ecrypt?: e

File to encrypt: img.png

Password: 123


The file encrypted is stored in the folder with name: (encrypted)photo.jpg. This is clearly mentioned in the figure below:

encrypted file

The same file is used for decryption with the password which is used for encryption. If the password doesn’t match the authentication fails file will be decrypted with a different password producing a result which is different than original plain text.

Output of decryption with correct password entry:


Would you like to (E)ncrypt or (D)ecrypt?: D

File to decrypt: (encrypted)img.png

Password: 123


The output of decryption with incorrect password entry:


Would you like to (E)ncrypt or (D)ecrypt?: D

File to decrypt: (encrypted)img.png

Password: hello


The above method is said to be insecure so we need a secured methodology or functionality to encrypt and decrypt the message using AES(Advanced Encryption Standards).

The complete logic of this symmetric cryptography algorithm is described in later chapters but we will implement an inbuilt module called “pyAesCrypt” for performing the operation of encryption and decryption of a text file say “data.txt”. pyAesCrypt is a Python 3 file-encryption module and script that uses AES256-CBC to encrypt/decrypt files and binary streams.

The installation command is as follows:

pip install pyAesCrypt

Output of installation:

C:\Users\Radhika\PycharmProjects-demo\Cryptographic-algorithms-with-python>pip install pyAesCrypt

Collecting pyAesCrypt


Requirement already satisfied: cryptography in c:\python36\lib\site-packages (from pyAesCrypt) (2.3.1)

Requirement already satisfied: asn1crypto>=0.21.0 in c:\python36\lib\site-packages (from cryptography->pyAesCrypt) (0.24.0)

Requirement already satisfied: six>=1.4.1 in c:\python36\lib\site-packages (from cryptography->pyAesCrypt) (1.11.0)

Requirement already satisfied: cffi!=1.11.3,>=1.7 in c:\python36\lib\site-packages (from cryptography->pyAesCrypt) (1.11.5)

Requirement already satisfied: idna>=2.1 in c:\python36\lib\site-packages (from cryptography->pyAesCrypt) (2.7)

Requirement already satisfied: pycparser in c:\python36\lib\site-packages (from cffi!=1.11.3,>=1.7->cryptography->pyAesCrypt) (2.18)

Installing collected packages: pyAesCrypt

Successfully installed pyAesCrypt-0.4

Now we will be focusing on the encryption and decryption of file called “data.txt” which is included in our folder. The contents included in data.txt is mentioned below:


Now we will be focusing on encrypting this file using “PyAesCrypt” module in Python which is displayed below:

import pyAesCrypt
from os import stat, remove
# encryption/decryption buffer size
bufferSize = 64 * 1024
password = “pwd”
# encryption of file data.txt
with open(“data.txt”, “rb”) as fIn:
with open(“data.txt.aes”, “wb”) as fOut:
pyAesCrypt.encryptStream(fIn, fOut, password, bufferSize)
# get encrypted file size
encFileSize = stat(“data.txt.aes”).st_size
print(encFileSize) #prints file size
# decryption of file data.aeswith open(“data.txt.aes”, “rb”) as fIn:
with open(“dataout.txt”, “wb”) as fOut:
# decrypt file stream
pyAesCrypt.decryptStream(fIn, fOut, password, bufferSize, encFileSize)
except ValueError:
# remove output file on error





The folder will display three files are mentioned below:


The decryption of file is done with creation of new file “dataout.txt” file which created the same content as included in “data.txt” file as shown below:

decryption file

The encryption of file using AES module is created in “data.txt.aes” is displayed below:



The file loaded is in UTF-8 format as displayed above which provides higher security standards.

Read More: Jobs In Demand For 2020 & Beyond: 15 Careers You Can’t Ignore!!


Encryption of images or file format is important if it includes any confidential information. The standard encryption technique which was followed earlier includes a lack of security which is achieved in the “PyAesCrypt” module and the demonstration displayed was for “.txt” messages but can be applied for any image format also.

Python is a highly popular language among programmers and is just behind Rust in terms of most loved programming languages. The simplicity of the language and shorter codes are some of the key reasons for its popularity. The jobs for Python developers are also growing and salaries can reach as high as $110,000 per year. The language is also handy when it comes to AI, Machine Learning and data science.

You can try learning more about Python through E-Books or books. Or you can also try out some of our tutorials pertaining to Python such as the “Python Programming An Expert Guide on Python” which comes with over 9 hours of video and includes topics such as Strings and list data types, variables, closures, functions, files, loops and much more.

Also, if you are familiar with the essentials of Python programming, you can go for the “Beyond Basic Programming – Intermediate Python” which comes over 3 hours of video and includes 7 sections such as cross-cutting tools, intermediate programming, functional programming, applications and much more.


  1. I want to create a django app which performs image enc and dec for that image i uploaded. Please suggestion what to do, I have tried this but it gives me error of TemporaryUploadedFile. Do reply any body a solution to this.


Please enter your comment!
Please enter your name here