Open In App

Encrypt and Decrypt Image using Python

Last Updated : 08 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will encrypt/decrypt an image using simple mathematical logic. It requires two things, data, and key, and when XOR operation is applied on both the operands i.e data and key, the data gets encrypted but when the same process is done again with the same key-value data gets decrypted.

Encryption

It is nothing but a simple process in which we convert our data or information into secret code to prevent it from unauthorized access and keep it private and secure.

First, we will select an image, and then we will convert that image into a byte array due to which the image data will be totally converted into numeric form, and then we can easily apply the XOR operation to it. Now, whenever we will apply the XOR function on each value of the byte array then the data will be changed due to which we will be unable to access it. But we should remember one thing here our encryption key plays a very important role without that key we can not decrypt our image. It acts as a password to decrypt it.

The below program depicts the basic approach to encryption:

Python3




# Assign values
data = 1281
key = 27
 
# Display values
print('Original Data:', data)
print('Key:', key)
 
# Encryption
data = data ^ key
print('After Encryption:', data)
 
# Decryption
data = data ^ key
print('After Decryption:', data)


Output:

Original Data: 1281
Key: 27
After Encryption: 1306
After Decryption: 1281

Here in the above program, as we can see how XOR operation works, it takes two variables data and a key, whenever we perform XOR operation on them for the first time we get encrypted data. Then when we perform the XOR operation between our data and key again, we get the same value as our input variable data (decrypted data). The same logic will be applicable to a byte array of Images during encryption and decryption.

Executable code for Encryption: 

Python3




# try block to handle exception
try:
    # take path of image as a input
    path = input(r'Enter path of Image : ')
     
    # taking encryption key as input
    key = int(input('Enter Key for encryption of Image : '))
     
    # print path of image file and encryption key that
    # we are using
    print('The path of file : ', path)
    print('Key for encryption : ', key)
     
    # open file for reading purpose
    fin = open(path, 'rb')
     
    # storing image data in variable "image"
    image = fin.read()
    fin.close()
     
    # converting image into byte array to
    # perform encryption easily on numeric data
    image = bytearray(image)
 
    # performing XOR operation on each value of bytearray
    for index, values in enumerate(image):
        image[index] = values ^ key
 
    # opening file for writing purpose
    fin = open(path, 'wb')
     
    # writing encrypted data in image
    fin.write(image)
    fin.close()
    print('Encryption Done...')
 
     
except Exception:
    print('Error caught : ', Exception.__name__)


 Output:                   

Enter path of Image : C:\Users\lenovo\Pictures\Instagram\enc.png
Enter Key for encryption of Image : 22
The path of file :  C:\Users\lenovo\Pictures\Instagram\enc.png
Key for encryption :  22
Encryption done...

Here in the above code first we take the path of the image and encryption key as input from the user then we use the file handling concept to handle the binary file and open that file for reading purposes then read the binary data of the image and store it in image variable. Now we convert that binary form of data into a byte array, then we apply the XOR operation on each value of the byte array which changes the data due to which we will be unable to open the image. 

Decryption 

It is nothing but a process of converting our encrypted data into a readable form. Here we will again apply the same XOR operation on an encrypted image to decrypt it. But always remember that our encryption key and decryption key must be the same.

Executable Code for Decryption: 

Python3




# try block to handle the exception
try:
    # take path of image as a input
    path = input(r'Enter path of Image : ')
     
    # taking decryption key as input
    key = int(input('Enter Key for encryption of Image : '))
     
    # print path of image file and decryption key that we are using
    print('The path of file : ', path)
    print('Note : Encryption key and Decryption key must be same.')
    print('Key for Decryption : ', key)
     
    # open file for reading purpose
    fin = open(path, 'rb')
     
    # storing image data in variable "image"
    image = fin.read()
    fin.close()
     
    # converting image into byte array to perform decryption easily on numeric data
    image = bytearray(image)
 
    # performing XOR operation on each value of bytearray
    for index, values in enumerate(image):
        image[index] = values ^ key
 
    # opening file for writing purpose
    fin = open(path, 'wb')
     
    # writing decryption data in image
    fin.write(image)
    fin.close()
    print('Decryption Done...')
 
 
except Exception:
    print('Error caught : ', Exception.__name__)


Output:

Enter path of Image : C:\Users\lenovo\Pictures\Instagram\enc.png
Enter Key for Decryption of Image : 22
The path of file :  C:\Users\lenovo\Pictures\Instagram\enc.png
Note : Encryption key and Decryption key must be same.
Key for Decryption :  22
Decryption done...

 Here in the above Decryption program, we use the same procedure that we use during the Encryption of image.’

Below is the video which depicts the functionality of the above programs using a given image and a key.  



Similar Reads

Encrypt and Decrypt Files using Python
Encryption is the act of encoding a message so that only the intended users can see it. We encrypt data because we don't want anyone to see or access it. We will use the cryptography library to encrypt a file. The cryptography library uses a symmetric algorithm to encrypt the file. In the symmetric algorithm, we use the same key to encrypt and decr
3 min read
Encrypt and Decrypt PDF using PyPDF2
PDF (Portable Document Format) is one of the most used file formats for storing and sending documents. They are commonly used for many purposes such as eBooks, Resumes, Scanned documents, etc. But as we share pdf to many people, there is a possibility of its data getting leaked or stolen. So, it's necessary to password protect our PDF files so that
4 min read
How to Encrypt and Decrypt Strings in Python?
In this article, we will learn about Encryption, Decryption and implement them with Python. Encryption: Encryption is the process of encoding the data. i.e converting plain text into ciphertext. This conversion is done with a key called an encryption key. Decryption: Decryption is the process of decoding the encoded data. Converting the ciphertext
4 min read
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values & Binary forms for all printable characters, which allows us to operate bit-wise logic like XOR and most encryption/decryption algorithms depend on. The Key is XOR-operated on the plain text to produce the encrypted text. Only Parameters required to encrypt a plain text using this technique: P
2 min read
How to encrypt passwords in a Spring Boot project using Jasypt
In this article, we will learn how to encrypt data in Spring Boot application config files like application.properties or application.yml. Inside those files, we can encrypt username, password, etc. You often come across developing projects where you have to connect to databases like MongoDB, etc, and store the authentic password of the DB connecti
4 min read
Encrypt the String according to the given algorithm in Python
Given a string s, the task is to encrypt the string in the following way. Let the string be "apple". Step 1: Reverse the input: "elppa" Step 2: Replace all vowels using the following chart: a => 0 e => 1 i => 2 o => 2 u => 3 Resultant string - "1lpp0" Step 3: Add "aca" to the end of the word: Resultant String: "1lpp0aca" Examples: In
2 min read
Java Program to Encrypt Password in Configuration Files
Passwords provide the first line of defense against unauthorized access to your computer and personal information. The stronger your password, the more protected your computer will be from hackers and malicious software. Every website or software application requires a password in order to authenticate the valid user. But while creating a password,
6 min read
Convert Text Image to Hand Written Text Image using Python
In this article, we are going to see how to convert text images to handwritten text images using PyWhatkit, Pillow, and Tesseract in Python. Module needed: Pytesseract: Sometimes known as Python-tesseract, is a Python-based optical character recognition (OCR) program. It can read and recognize text in photos, license plates, and other documents. To
2 min read
Image Segmentation using Python's scikit-image module
The process of splitting images into multiple layers, represented by a smart, pixel-wise mask is known as Image Segmentation. It involves merging, blocking, and separating an image from its integration level. Splitting a picture into a collection of Image Objects with comparable properties is the first stage in image processing. Scikit-Image is the
14 min read
How to merge a transparent PNG image with another image using PIL?
This article discusses how to put a transparent PNG image with another image. This is a very common operation on images. It has a lot of different applications. For example, adding a watermark or logo on an image. To do this, we are using the PIL module in Python. In which we use some inbuilt methods and combine the images in such a way that it loo
2 min read
Practice Tags :