Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Encrypt and Decrypt PDF using PyPDF2
Next article icon

Encrypt and Decrypt Image using Python

Last Updated : 08 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
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.  

https://media.geeksforgeeks.org/wp-content/uploads/20201013225712/video-20201013-223339_XTxPBdfH.mp4


Next Article
Encrypt and Decrypt PDF using PyPDF2
author
ronilpatil
Improve
Article Tags :
  • Python
  • cryptography
  • python-utility
Practice Tags :
  • python

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
    3 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 de
    6 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 n
    4 min read
  • Convert image to binary using Python
    In this article, we are going to convert the image into its binary form. A binary image is a monochromatic image that consists of pixels that can have one of exactly two colors, usually black and white. Binary images are also called bi-level or two-level. This means that each pixel is stored as a si
    1 min read
  • How To Encode And Decode A Message using Python?
    Encryption is the process of converting a normal message (plain text) into a meaningless message (Ciphertext). Whereas, Decryption is the process of converting a meaningless message (Cipher text) into its original form (Plain text). In this article, we will take forward the idea of encryption and de
    3 min read
  • Create a Credential file using Python
    A credential file is nothing but just a configuration file with a tad bit of encryption and an unseen security structure in the backend. There might be a situation where you might come across these kinds of files while using some kind of cloud platforms. All you do to login to the instance or give t
    5 min read
  • Generate Captcha Using Python
    In this article, we are going to see how to generate a captcha using Python package captcha to generate our own CAPTCHA (Completely Automated Public Turing Test to Tell Computers and Humans Apart) in picture form. CAPTCHA is a form of challenge-response authentication security mechanism. CAPTCHA pre
    2 min read
  • Python | Crop image using pillow
    In this article, we will learn to crop an image using pillow library. Cropping an image means to select a rectangular region inside an image and removing everything outside the rectangle. To crop an image we make use of crop() method on image objects. Syntax : IMG.crop(box_tuple) Parameters : Image_
    1 min read
  • Convert PDF to Image using Python
    Many tools are available on the internet for converting a PDF to an image. In this article, we are going to write code for converting pdf to image and make a handy application in python. Before writing the code we need to install the required module pdf2image and poppler. Modules Neededpdf2image 1.1
    2 min read
  • Cropping an Image in a circular way using Python
    In this article, we will learn to crop an image circularly using a pillow library. Cropping an image circularly means selecting a circular region inside an image and removing everything outside the circle.  Approach: If you have an L mode image, the image becomes grayscale. So we create a new image
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences