#!
/usr/bin/env python
# ----------------- Header Files ---------------------#
from __future__ import division, print_function, unicode_literals
import sys
import random
import argparse
import logging
from tkinter import * # Changed from Tkinter to tkinter for Python 3
from tkinter import filedialog # Changed from tkFileDialog to filedialog for
Python 3
from tkinter import messagebox # Changed from tkMessageBox to messagebox for
Python 3
import os
from PIL import Image
import math
from [Link] import AES
from [Link] import unpad
from tkinter import Tk, Button, LEFT, RIGHT, Entry, Label, Message, Canvas
import hashlib
import binascii
import numpy as np
global password
def load_image(name):
return [Link](name)
# ----------------- Functions for encryption ---------------------#
def prepare_message_image(image, size):
if size != [Link]:
image = [Link](size, [Link])
return image
def generate_secret(size, secret_image=None):
width, height = size
new_secret_image = [Link](mode="RGB", size=(width * 2, height * 2))
for x in range(0, 2 * width, 2):
for y in range(0, 2 * height, 2):
color1 = [Link](255)
color2 = [Link](255)
color3 = [Link](255)
new_secret_image.putpixel((x, y), (color1, color2, color3))
new_secret_image.putpixel((x + 1, y), (255 - color1, 255 - color2,
255 - color3))
new_secret_image.putpixel((x, y + 1), (255 - color1, 255 - color2,
255 - color3))
new_secret_image.putpixel((x + 1, y + 1), (color1, color2,
color3))
return new_secret_image
def generate_ciphered_image(secret_image, prepared_image):
width, height = prepared_image.size
ciphered_image = [Link](mode="RGB", size=(width * 2, height * 2))
for x in range(0, width * 2, 2):
for y in range(0, height * 2, 2):
sec = secret_image.getpixel((x, y))
msssg = prepared_image.getpixel((int(x / 2), int(y / 2)))
color1 = (msssg[0] + sec[0]) % 256
color2 = (msssg[1] + sec[1]) % 256
color3 = (msssg[2] + sec[2]) % 256
ciphered_image.putpixel((x, y), (color1, color2, color3))
ciphered_image.putpixel((x + 1, y), (255 - color1, 255 - color2,
255 - color3))
ciphered_image.putpixel((x, y + 1), (255 - color1, 255 - color2,
255 - color3))
ciphered_image.putpixel((x + 1, y + 1), (color1, color2, color3))
return ciphered_image
def generate_image_back(secret_image, ciphered_image):
width, height = secret_image.size
new_image = [Link](mode="RGB", size=(int(width / 2), int(height / 2)))
for x in range(0, width, 2):
for y in range(0, height, 2):
sec = secret_image.getpixel((x, y))
cip = ciphered_image.getpixel((x, y))
color1 = (cip[0] - sec[0]) % 256
color2 = (cip[1] - sec[1]) % 256
color3 = (cip[2] - sec[2]) % 256
new_image.putpixel((int(x / 2), int(y / 2)), (color1, color2,
color3))
return new_image
#------------------------Encryption -------------------#
def level_one_encrypt(Imagename):
message_image = load_image(Imagename)
size = message_image.size
width, height = size
secret_image = generate_secret(size)
secret_image.save("[Link]")
prepared_image = prepare_message_image(message_image, size)
ciphered_image = generate_ciphered_image(secret_image, prepared_image)
ciphered_image.save("2-share_encrypt.jpeg")
# -------------------- Construct Encrypted Image ----------------#
def construct_enc_image(ciphertext, relength, width, height):
asciicipher = [Link](ciphertext)
def replace_all(text, dic):
for i, j in [Link]():
text = [Link]([Link](), [Link]())
return text
# use replace function to replace ascii cipher characters with numbers
reps = {'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5', 'f': '6', 'g':
'7', 'h': '8', 'i': '9', 'j': '10',
'k': '11', 'l': '12', 'm': '13', 'n': '14', 'o': '15', 'p': '16',
'q': '17', 'r': '18', 's': '19',
't': '20', 'u': '21', 'v': '22', 'w': '23', 'x': '24', 'y': '25',
'z': '26'}
asciiciphertxt = replace_all(asciicipher, reps)
# construct encrypted image
step = 3
encimageone = [asciiciphertxt[i:i + step] for i in range(0,
len(asciiciphertxt), step)]
# if the last pixel RGB value is less than 3-digits, add a digit a 1
if int(encimageone[len(encimageone) - 1]) < 100:
encimageone[len(encimageone) - 1] += b"1"
# check to see if we can divide the string into partitions of 3 digits.
if not, fill in with some garbage RGB values
if len(encimageone) % 3 != 0:
while (len(encimageone) % 3 != 0):
[Link]("101")
encimagetwo = [(int(encimageone[int(i)]), int(encimageone[int(i + 1)]),
int(encimageone[int(i + 2)])) for i in
range(0, len(encimageone), step)]
print(len(encimagetwo))
while (int(relength) != len(encimagetwo)):
[Link]()
encim = [Link]("RGB", (int(width), int(height)))
[Link](encimagetwo)
[Link]("visual_encrypt.jpeg")
#------------------------- Visual-encryption -------------------------#
def encrypt(imagename, password):
plaintext = list()
plaintextstr = b""
im = [Link](imagename)
pix = [Link]()
width = [Link][0]
height = [Link][1]
# break up the image into a list, each with pixel values and then append
to a string
for y in range(0, height):
for x in range(0, width):
print(pix[x, y])
[Link](pix[x, y])
print(width)
print(height)
# add 100 to each tuple value to make sure each are 3 digits long.
for i in range(0, len(plaintext)):
for j in range(0, 3):
aa = int(plaintext[i][j]) + 100
plaintextstr += str(aa).encode()
# length save for encrypted image reconstruction
relength = len(plaintext)
# append dimensions of image for reconstruction after decryption
plaintextstr += b"h" + str(height).encode() + b"h" + b"w" +
str(width).encode() + b"w"
# make sure that plantextstr length is a multiple of 16 for AES. if not,
append "n".
while (len(plaintextstr) % 16 != 0):
plaintextstr += b"n"
# encrypt plaintext
obj = [Link](password, AES.MODE_CBC, b'This is an IV456')
ciphertext = [Link](plaintextstr)
# write ciphertext to file for analysis
cipher_name = imagename + ".crypt"
with open(cipher_name, 'wb') as g: # Changed mode to 'wb' for writing
bytes
[Link](ciphertext)
construct_enc_image(ciphertext, relength, width, height)
print("Visual Encryption done.......")
level_one_encrypt("visual_encrypt.jpeg")
print("2-Share Encryption done.......")
# ---------------------- decryption ---------------------- #
def decrypt(ciphername, password):
# Open the secret image and the 2-share encrypted image
secret_image = [Link]("[Link]")
ima = [Link]("2-share_encrypt.jpeg")
new_image = generate_image_back(secret_image, ima)
new_image.save("2-share_decrypt.jpeg")
print("2-share Decryption done....")
try:
# Open the encrypted file in binary mode
with open(ciphername, 'rb') as cipher_file:
ciphertext = cipher_file.read()
# Decrypt ciphertext with password
obj2 = [Link](password, AES.MODE_CBC, b'This is an IV456')
decrypted = [Link](ciphertext)
# Parse the decrypted text back into bytes
decrypted = [Link]().replace("n", "").encode()
# Extract dimensions of images
newwidth = [Link](b"w")[1].decode()
newheight = [Link](b"h")[1].decode()
# Replace height and width indicators with empty space in decrypted
plaintext
heightr = b"h" + [Link]() + b"h"
widthr = b"w" + [Link]() + b"w"
decrypted = [Link](heightr, b"")
decrypted = [Link](widthr, b"")
# Reconstruct the list of RGB tuples from the decrypted plaintext
step = 3
finaltextone = [decrypted[i:i + step] for i in range(0,
len(decrypted), step)]
finaltexttwo = [(int(finaltextone[i]) - 100, int(finaltextone[i + 1])
- 100, int(finaltextone[i + 2]) - 100) for i in range(0, len(finaltextone),
step)]
# Reconstruct image from list of pixel RGB tuples
newim = [Link]("RGB", (int(newwidth), int(newheight)))
[Link](finaltexttwo)
[Link]("visual_decrypt.jpeg")
print("Visual Decryption done......")
except Exception as e:
print("Error during decryption:", e)
# GUI stuff
def pass_alert():
[Link]("Password Alert", "Please enter a password.")
def image_open():
global file_path_e
enc_pass = [Link]()
if enc_pass == "":
pass_alert()
else:
password = hashlib.sha256(enc_pass.encode()).digest()
filename = [Link]()
file_path_e = [Link](filename)
encrypt(filename, password)
def cipher_open():
global file_path_d
dec_pass = [Link]()
if dec_pass == "":
pass_alert()
else:
password = hashlib.sha256(dec_pass.encode()).digest()
filename = [Link]()
file_path_d = [Link](filename)
decrypt(filename, password)
class App:
def __init__(self, master):
global passg
title = "Image Encryption"
author = "Made by Aditya"
msgtitle = Message(master, text=title)
[Link](font=('helvetica', 17, 'bold'), width=200)
msgauthor = Message(master, text=author)
[Link](font=('helvetica', 10), width=200)
canvas_width = 200
canvas_height = 50
w = Canvas(master,
width=canvas_width,
height=canvas_height)
[Link]()
[Link]()
[Link]()
passlabel = Label(master, text="Enter Encrypt/Decrypt Password:")
[Link]()
passg = Entry(master, show="*", width=20)
[Link]()
[Link] = Button(master,
text="Encrypt", fg="black",
command=image_open, width=25, height=5)
[Link](side=LEFT)
[Link] = Button(master,
text="Decrypt", fg="black",
command=cipher_open, width=25, height=5)
[Link](side=RIGHT)
# Main function
if __name__ == "__main__":
root = Tk()
root.wm_title("Image Encryption")
app = App(root)
[Link]()
name__ == "__main__":