File Encryption And Decryption Using Python

1
4698
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.

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

Downloading https://files.pythonhosted.org/packages/fc/bb/0b812dc02e6357606228edfbf5808f5ca0a675a84273578c3a199e841cd8/crypto-1.4.1-py2.py3-none-any.whl

Collecting shellescape (from Crypto)

Downloading https://files.pythonhosted.org/packages/51/b6/986c99a10040beaaefca1ad6c93bd7738cb8e4f52f6caed13d3ed1caa7e4/shellescape-3.4.1-py2.py3-none-any.whl

Collecting Naked (from Crypto)

Downloading https://files.pythonhosted.org/packages/02/36/b8107b51adca73402ec1860d88f41d958e275e60eea6eeaa9c39ddb89a40/Naked-0.1.31-py2.py3-none-any.whl (590kB)

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

Collecting requests (from Naked->Crypto)

Using cached https://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69c4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl

Collecting pyyaml (from Naked->Crypto)

Cache entry deserialization failed, entry ignored

Downloading https://files.pythonhosted.org/packages/fb/51/0c49c6caafe8d9a27ad9b0ca9f91adda5a5072b9efbbe7585fb97a4c71c4/PyYAML-3.13-cp36-cp36m-win32.whl (188kB)

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

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

Using cached https://files.pythonhosted.org/packages/bd/c9/6fdd990019071a4a32a5e7cb78a1d92c53851ef4f56f62a3486e6a7d8ffb/urllib3-1.23-py2.py3-none-any.whl

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

Using cached https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl

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

Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl

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

Downloading https://files.pythonhosted.org/packages/df/f7/04fee6ac349e915b82171f8e23cee63644d83663b34c539f7a09aed18f9e/certifi-2018.8.24-py2.py3-none-any.whl (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(
16)
IV = Random.new().read(
16)

encryptor = AES.new(key, AES.MODE_CBC, IV)

with open(filename, ‘rb’) as infile:
with open(outputFile, ‘wb’) as outfile:
outfile.write(filesize.encode(
‘utf-8’))
outfile.write(IV)

while True:
chunk = infile.read(chunksize)

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

outfile.write(encryptor.encrypt(chunk))

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

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

decryptor = AES.new(key, AES.MODE_CBC, IV)

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

if len(chunk) == 0:
break

outfile.write(decryptor.decrypt(chunk))
outfile.truncate(filesize)

def getKey(password):
hasher = SHA256.new(password.encode(
‘utf-8’))
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: “)
encrypt(getKey(password)
, filename)
print(“Done.”)
elif choice == ‘D’ or choice == ‘d’:
filename = input(
“File to decrypt: “)
password = input(
“Password: “)
decrypt(getKey(password)
, filename)
print(“Done.”)
else:
print(“No Option selected, closing…”)

if __name__ == ‘__main__’:
Main()

Output for Encryption:

C:\Users\Radhika\PycharmProjects-demo\Cryptographic-algorithms-with-python>python fileEncryption.py

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

File to encrypt: img.png

Password: 123

Done.

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:

C:\Users\Radhika\PycharmProjects-demo\Cryptographic-algorithms-with-python>python fileEncryption.py

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

File to decrypt: (encrypted)img.png

Password: 123

Done.

The output of decryption with incorrect password entry:

C:\Users\Radhika\PycharmProjects-demo\Cryptographic-algorithms-with-python>python fileEncryption.py

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

File to decrypt: (encrypted)img.png

Password: hello

Done.

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

Downloading https://files.pythonhosted.org/packages/fa/da/3dfc14c6409a86fdf49b903b4183372558ee996a25cf737e4817861d2944/pyAesCrypt-0.4-py3-none-any.whl

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:

file

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:
try:
# decrypt file stream
pyAesCrypt.decryptStream(fIn, fOut, password, bufferSize, encFileSize)
except ValueError:
# remove output file on error
remove(“dataout.txt”)

Output:

C:\Users\Radhika\PycharmProjects-demo\Cryptographic-algorithms-with-python>python fileEncryptionDecryption.py

309

 

The folder will display three files are mentioned below:

folder

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:

AESߺ����hV�<EM�l
з���B‑�_x0016_����c\�����z­rR��Y�4�

 

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

SUMMARY:

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 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here