Omnibus commited on
Commit
dd877b2
·
1 Parent(s): d6bd8fe

Create encrypt.py

Browse files
Files changed (1) hide show
  1. encrypt.py +205 -0
encrypt.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from Crypto.PublicKey import RSA
2
+ from Crypto.Random import get_random_bytes
3
+ from Crypto.Cipher import AES, PKCS1_OAEP
4
+ from Crypto.Hash import RIPEMD160, SHA256
5
+ import base58
6
+ import base64
7
+ import cv2
8
+ import numpy as np
9
+ import os
10
+ import uuid
11
+ import qrcode as qr
12
+ import math
13
+ from PIL import ImageFont, ImageDraw, Image
14
+
15
+ def process(img,font_text,font_fac,font_x,font_y,font_col,font_op):
16
+ img.save('tmp.png')
17
+ img = Image.open('tmp.png').convert("RGBA")
18
+ im=img
19
+ txt = Image.new('RGBA', im.size, (255,255,255,0))
20
+ w, h = im.size
21
+ h1 = font_col.strip("#")
22
+ rgb_tup = tuple(int(h1[i:i+2], 16) for i in (0, 2, 4))
23
+ a,b,c = rgb_tup
24
+ t_fill = (a,b,c,font_op)
25
+ x = int(font_x)
26
+ y = int(font_y)
27
+ draw = ImageDraw.Draw(txt)
28
+ text = f'{font_text}'
29
+ font_size=font_fac
30
+ font = ImageFont.truetype("./fonts/SansitaOne.ttf", int(font_size))
31
+ size = font.getsize(text)
32
+ draw.text((x-size[0]/2, y),text, font = font, fill=t_fill)
33
+ combined = Image.alpha_composite(im, txt)
34
+ return combined
35
+
36
+ def textover(im,txt1="",txt2=""):
37
+ im = Image.open(im)
38
+ inp=1
39
+ hh=0
40
+ hhh=25
41
+ cnt = inp
42
+ font_a = 30
43
+ font_b = 10
44
+ if cnt >0:
45
+ font_a = font_a + (cnt * 2)
46
+ font_b = font_b + (cnt * 2)
47
+ #hh = hh-int(cnt/2)
48
+ hhh = hhh+int(cnt/2)
49
+ w,h = im.size
50
+ print (w)
51
+ print (h)
52
+ font_x = (w/2)
53
+ font_y = h-hhh
54
+ out = process(im,txt1,font_fac=font_a,font_x=font_x,font_y=hh,font_col="#000000",font_op=255)
55
+ out = process(out,txt2,font_fac=font_b,font_x=font_x,font_y=font_y,font_col="#000000",font_op=255)
56
+ return out
57
+
58
+ def make_qr(txt=None,color_f=None,color_b=None):
59
+ qrm = qr.QRCode(box_size=10,error_correction=qr.constants.ERROR_CORRECT_H)
60
+ if color_f == None:
61
+ color_f = "#000"
62
+ if color_b == None:
63
+ color_b = "#fff"
64
+ if txt != None and txt != "" and data == None:
65
+ out = f'{txt}'
66
+ print (f'txt {out}')
67
+ qrm.add_data(out)
68
+ qrm.make(fit=True)
69
+ img1 = qrm.make_image(fill_color=color_f, back_color=color_b)
70
+ img1.save("im2.png")
71
+ return "im2.png"
72
+
73
+ def to_bin(data):
74
+ """Convert `data` to binary format as string"""
75
+ if isinstance(data, str):
76
+ return ''.join([ format(ord(i), "08b") for i in data ])
77
+ elif isinstance(data, bytes):
78
+ return ''.join([ format(i, "08b") for i in data ])
79
+ elif isinstance(data, np.ndarray):
80
+ return [ format(i, "08b") for i in data ]
81
+ elif isinstance(data, int) or isinstance(data, np.uint8):
82
+ return format(data, "08b")
83
+ else:
84
+ raise TypeError("Type not supported.")
85
+ def decode(image_name,txt=None):
86
+ BGRimage = cv2.imread(image_name)
87
+ image = cv2.cvtColor(BGRimage, cv2.COLOR_BGR2RGB)
88
+ binary_data = ""
89
+ for row in image:
90
+ for pixel in row:
91
+ r, g, b = to_bin(pixel)
92
+ binary_data += r[-1]
93
+ binary_data += g[-1]
94
+ binary_data += b[-1]
95
+ all_bytes = [ binary_data[i: i+8] for i in range(0, len(binary_data), 8) ]
96
+ decoded_data = ""
97
+ for byte in all_bytes:
98
+ decoded_data += chr(int(byte, 2))
99
+ if decoded_data[-5:] == "=====":
100
+ break
101
+ this = decoded_data[:-5].split("#####",1)[0]
102
+ this = eval(this)
103
+ enc_in=this
104
+ return this
105
+
106
+ def encode(image_name, secret_data,txt=None):
107
+ BGRimage = cv2.imread(image_name)
108
+ image = cv2.cvtColor(BGRimage, cv2.COLOR_BGR2RGB)
109
+ n_bytes = image.shape[0] * image.shape[1] * 3 // 8
110
+ print("[*] Maximum bytes to encode:", n_bytes)
111
+ secret_data1=secret_data
112
+ while True:
113
+ if len(secret_data1)+5 < (n_bytes):
114
+ secret_data1 = f'{secret_data1}#####'
115
+ elif len(secret_data1)+5 >= (n_bytes):
116
+ break
117
+ secret_data = secret_data1
118
+ if len(secret_data) > n_bytes:
119
+ return image_name, gr.Markdown.update("""<center><h3>Input image is too large""")
120
+ secret_data += "====="
121
+ data_index = 0
122
+ binary_secret_data = to_bin(secret_data)
123
+ data_len = len(binary_secret_data)
124
+ for row in image:
125
+ for pixel in row:
126
+ r, g, b = to_bin(pixel)
127
+ if data_index < data_len:
128
+ pixel[0] = int(r[:-1] + binary_secret_data[data_index], 2)
129
+ data_index += 1
130
+ if data_index < data_len:
131
+ pixel[1] = int(g[:-1] + binary_secret_data[data_index], 2)
132
+ data_index += 1
133
+ if data_index < data_len:
134
+ pixel[2] = int(b[:-1] + binary_secret_data[data_index], 2)
135
+ data_index += 1
136
+ if data_index >= data_len:
137
+ break
138
+ return image
139
+
140
+ def conv_im(im,data):
141
+ uniqnum = uuid.uuid4()
142
+ byte_size = len(data)
143
+ data_pixels = byte_size*4
144
+ data_sq = int(math.sqrt(data_pixels))
145
+ data_pad = data_sq+100
146
+ qr_im = im
147
+ img1 = Image.open(qr_im)
148
+ imgw = img1.size[0]
149
+ imgh = img1.size[1]
150
+ if data_pad > imgw or data_pad > imgh :
151
+ img1 = img1.resize((int(data_pad),int(data_pad)), Image.Resampling.LANCZOS)
152
+ print (img1.size)
153
+ img1.save(f'tmpim{uniqnum}.png')
154
+ with open(f'tmpim{uniqnum}.png', "rb") as image_file:
155
+ encoded_string = base64.b64encode(image_file.read())
156
+ image_file.close()
157
+ im_out = encode(f'tmpim{uniqnum}.png',data)
158
+ return im_out
159
+
160
+ def calculate_hash(data, hash_function: str = "sha256") -> str:
161
+ if type(data) == str:
162
+ data = bytearray(data, "utf-8")
163
+ if hash_function == "sha256":
164
+ h = SHA256.new()
165
+ h.update(data)
166
+ return h.hexdigest()
167
+ if hash_function == "ripemd160":
168
+ h = RIPEMD160.new()
169
+ h.update(data)
170
+ return h.hexdigest()
171
+
172
+ def encrypt_text(data,pub_im,mes_im=None):
173
+ uniq=uuid.uuid4()
174
+ pub_key = decode(pub_im)
175
+ data = data.encode("utf-8")
176
+ recipient_key = RSA.import_key(pub_key)
177
+ session_key = get_random_bytes(16)
178
+ cipher_rsa = PKCS1_OAEP.new(recipient_key)
179
+ enc_session_key = cipher_rsa.encrypt(session_key)
180
+ cipher_aes = AES.new(session_key, AES.MODE_EAX)
181
+ ciphertext, tag = cipher_aes.encrypt_and_digest(data)
182
+ file_out = open(f"{uniq}encrypted_data.bin", "wb")
183
+ [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
184
+ file_out.close()
185
+ doc_name = f"{uniq}encrypted_data.bin"
186
+ with open(doc_name, "rb") as file:
187
+ file_data =(file.read())
188
+ #print (f'file_data::{file_data}')
189
+ if mes_im == None:
190
+ qr_link="test"
191
+ #trans_im1.save("trans_im.png")
192
+ hash_1 = calculate_hash(pub_key, hash_function="sha256")
193
+ hash_2 = calculate_hash(hash_1, hash_function="ripemd160")
194
+ address = base58.b58encode(hash_2)
195
+ add_label = str(address)
196
+ add_label = add_label.strip("b").strip("'")
197
+ trans_im1=make_qr(txt=address, color_b="#ECFD08")
198
+ message_im = textover(trans_im1, "Message",add_label)
199
+ message_im.save(f"{uniq}private_key_im.png")
200
+ else:
201
+ im_mes=Image.open(mes_im)
202
+ im_mes.save(f"{uniq}private_key_im.png")
203
+ enc_qr = conv_im(f"{uniq}private_key_im.png",data=file_data)
204
+ file.close()
205
+ return str(file_data),enc_qr