from PIL import Image def encrypt(text, secret_key, img): image = Image.fromarray(img) image = image.convert('RGB') pixels = list(image.getdata()) binary_text = '' for char in text: binary_text+=format(ord(char), '08b') binary_secret = '' for char in secret_key: binary_secret+=format(ord(char), '08b') # print(binary_text) binary_text = binary_demorf(binary_text, binary_secret) binary_text = binary_text + binary_secret # print(binary_text) i = 0 print("number of bits we can store (binary_text + binary_secret): ",3*len(pixels)) new_pixels = [] for rgb in pixels: tcr = [] for clr in rgb: if i < len(binary_text): if binary_text[i] == '0': if clr % 2 != 0: clr -= 1 else: if clr % 2 == 0: clr += 1 i += 1 tcr += [clr] new_pixels += [tuple(tcr)] new_image = Image.new(image.mode, image.size) new_image.putdata(new_pixels) return new_image def decrypt(secret_key, img): image = Image.fromarray(img) pixels = list(image.getdata()) binary_secret = "" for(char) in secret_key: binary_secret += format(ord(char), '08b') binary_text = "" for rgb in pixels: for(clr) in rgb: if clr % 2 == 0: binary_text += '0' else: binary_text += '1' # print(binary_secret) text_pos = binary_text.split(binary_secret) if len(text_pos) == 1: return "No text found" else : bt = text_pos[0]; # print(bt) bt = binary_morf(bt, binary_secret) # print(bt) text = "" for i in range(0, len(bt), 8): text += chr(int(bt[i:i+8], 2)) return text def binary_demorf(binary_text,binary_secret): if len(binary_text) < len(binary_secret): return binary_text text = "" cidx =0 idx = 0 while idx < len(binary_text): ch = binary_text[idx] if cidx < len(binary_secret): if binary_secret[cidx] == ch: if cidx == len(binary_secret)-1: cidx = 0 if ch == '0': text += '1' else: text += '0' else: text += ch cidx += 1 idx += 1 else: if(binary_secret[0]==ch): cidx=1 else: cidx=0 text += ch idx+=1 else: text += ch idx+=1 return text def binary_morf(binary_text,binary_secret): if len(binary_text) < len(binary_secret): return binary_text t = binary_secret[:-1] # secret without the last digit l = binary_text.split(t) # split text with that # print(l) result = '' i = 0; while i < len(l): cr = "" if(i!=0): cr = l[i][1:] else: cr = l[i] if i != len(l)-1: result += cr + binary_secret; else: result += cr i+=1 return result