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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from Crypto.Signature import pkcs1_15
|
6 |
+
import binascii
|
7 |
+
import base58
|
8 |
+
import base64
|
9 |
+
import cv2
|
10 |
+
import numpy as np
|
11 |
+
from PIL import Image
|
12 |
+
import os
|
13 |
+
import uuid as uniq
|
14 |
+
import qrcode as qr
|
15 |
+
|
16 |
+
import math
|
17 |
+
|
18 |
+
############### qr ######################
|
19 |
+
|
20 |
+
def make_qr(txt=None,data=None,im_size=None,color_f=None,color_b=None):
|
21 |
+
|
22 |
+
qrm = qr.QRCode(box_size=10,error_correction=qr.constants.ERROR_CORRECT_H)
|
23 |
+
if color_f == None:
|
24 |
+
color_f = "#000"
|
25 |
+
if color_b == None:
|
26 |
+
color_b = "#fff"
|
27 |
+
if txt != None and txt != "" and data != None:
|
28 |
+
f = Image.open(f'{data}')
|
29 |
+
f.thumbnail((im_size,im_size))
|
30 |
+
f.save("tmp.jpg")
|
31 |
+
imr = open(f'tmp.jpg','rb')
|
32 |
+
out = f'{txt}+++{base64.b64encode(imr.read())}'
|
33 |
+
print (f'txt+data {out}')
|
34 |
+
qrm.add_data(out)
|
35 |
+
qrm.make(fit=True)
|
36 |
+
img1 = qrm.make_image(fill_color=color_f, back_color=color_b)
|
37 |
+
img1.save("im.png")
|
38 |
+
return "im.png"
|
39 |
+
if txt == None or txt == "" and data != None:
|
40 |
+
f = Image.open(f'{data}')
|
41 |
+
f.thumbnail((im_size,im_size))
|
42 |
+
f.save("tmp1.jpg")
|
43 |
+
imr = open(f'tmp1.jpg','rb')
|
44 |
+
out = f'+++{base64.b64encode(imr.read())}'
|
45 |
+
print (f'data {out}')
|
46 |
+
qrm.add_data(out)
|
47 |
+
qrm.make(fit=True)
|
48 |
+
img1 = qrm.make_image(fill_color=color_f, back_color=color_b)
|
49 |
+
img1.save("im1.png")
|
50 |
+
return "im1.png"
|
51 |
+
|
52 |
+
if txt != None and txt != "" and data == None:
|
53 |
+
out = f'{txt}'
|
54 |
+
print (f'txt {out}')
|
55 |
+
qrm.add_data(out)
|
56 |
+
qrm.make(fit=True)
|
57 |
+
img1 = qrm.make_image(fill_color=color_f, back_color=color_b)
|
58 |
+
img1.save("im2.png")
|
59 |
+
return "im2.png"
|
60 |
+
|
61 |
+
############ stegan ####################
|
62 |
+
def to_bin(data):
|
63 |
+
"""Convert `data` to binary format as string"""
|
64 |
+
if isinstance(data, str):
|
65 |
+
return ''.join([ format(ord(i), "08b") for i in data ])
|
66 |
+
elif isinstance(data, bytes):
|
67 |
+
return ''.join([ format(i, "08b") for i in data ])
|
68 |
+
elif isinstance(data, np.ndarray):
|
69 |
+
return [ format(i, "08b") for i in data ]
|
70 |
+
elif isinstance(data, int) or isinstance(data, np.uint8):
|
71 |
+
return format(data, "08b")
|
72 |
+
else:
|
73 |
+
raise TypeError("Type not supported.")
|
74 |
+
def decode(image_name,txt=None):
|
75 |
+
BGRimage = cv2.imread(image_name)
|
76 |
+
image = cv2.cvtColor(BGRimage, cv2.COLOR_BGR2RGB)
|
77 |
+
binary_data = ""
|
78 |
+
for row in image:
|
79 |
+
for pixel in row:
|
80 |
+
r, g, b = to_bin(pixel)
|
81 |
+
binary_data += r[-1]
|
82 |
+
binary_data += g[-1]
|
83 |
+
binary_data += b[-1]
|
84 |
+
all_bytes = [ binary_data[i: i+8] for i in range(0, len(binary_data), 8) ]
|
85 |
+
decoded_data = ""
|
86 |
+
for byte in all_bytes:
|
87 |
+
decoded_data += chr(int(byte, 2))
|
88 |
+
if decoded_data[-5:] == "=====":
|
89 |
+
break
|
90 |
+
this = decoded_data[:-5].split("#####",1)[0]
|
91 |
+
this = eval(this)
|
92 |
+
enc_in=this
|
93 |
+
return this
|
94 |
+
|
95 |
+
def encode(image_name, secret_data,txt=None):
|
96 |
+
BGRimage = cv2.imread(image_name)
|
97 |
+
image = cv2.cvtColor(BGRimage, cv2.COLOR_BGR2RGB)
|
98 |
+
n_bytes = image.shape[0] * image.shape[1] * 3 // 8
|
99 |
+
print("[*] Maximum bytes to encode:", n_bytes)
|
100 |
+
secret_data1=secret_data
|
101 |
+
#secret_data1=f'{secret_data}#{resultp}'
|
102 |
+
|
103 |
+
while True:
|
104 |
+
if len(secret_data1)+5 < (n_bytes):
|
105 |
+
secret_data1 = f'{secret_data1}#####'
|
106 |
+
elif len(secret_data1)+5 >= (n_bytes):
|
107 |
+
break
|
108 |
+
secret_data = secret_data1
|
109 |
+
if len(secret_data) > n_bytes:
|
110 |
+
return image_name, gr.Markdown.update("""<center><h3>Input image is too large""")
|
111 |
+
secret_data += "====="
|
112 |
+
data_index = 0
|
113 |
+
binary_secret_data = to_bin(secret_data)
|
114 |
+
data_len = len(binary_secret_data)
|
115 |
+
for row in image:
|
116 |
+
for pixel in row:
|
117 |
+
r, g, b = to_bin(pixel)
|
118 |
+
if data_index < data_len:
|
119 |
+
pixel[0] = int(r[:-1] + binary_secret_data[data_index], 2)
|
120 |
+
data_index += 1
|
121 |
+
if data_index < data_len:
|
122 |
+
pixel[1] = int(g[:-1] + binary_secret_data[data_index], 2)
|
123 |
+
data_index += 1
|
124 |
+
if data_index < data_len:
|
125 |
+
pixel[2] = int(b[:-1] + binary_secret_data[data_index], 2)
|
126 |
+
data_index += 1
|
127 |
+
if data_index >= data_len:
|
128 |
+
break
|
129 |
+
return image
|
130 |
+
|
131 |
+
def conv_im(im,data):
|
132 |
+
uniqnum = uniq.uuid4()
|
133 |
+
|
134 |
+
byte_size = len(data)
|
135 |
+
print (f'bytes:{byte_size}')
|
136 |
+
data_pixels = byte_size*4
|
137 |
+
print (f'pixels:{data_pixels}')
|
138 |
+
#data_sq=data_pixels/2
|
139 |
+
data_sq = int(math.sqrt(data_pixels))
|
140 |
+
data_pad = data_sq+100
|
141 |
+
print (f'square image:{data_pad}x{data_pad}')
|
142 |
+
|
143 |
+
qr_im = im
|
144 |
+
img1 = Image.open(qr_im)
|
145 |
+
imgw = img1.size[0]
|
146 |
+
imgh = img1.size[1]
|
147 |
+
print (f'qr Size:{img1.size}')
|
148 |
+
#img1.thumbnail((imgw*4,imgh*4), Image.Resampling.LANCZOS)
|
149 |
+
if data_pad > imgw or data_pad > imgh :
|
150 |
+
|
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 |
+
|
155 |
+
with open(f'tmpim{uniqnum}.png', "rb") as image_file:
|
156 |
+
encoded_string = base64.b64encode(image_file.read())
|
157 |
+
image_file.close()
|
158 |
+
im_out = encode(f'tmpim{uniqnum}.png',data)
|
159 |
+
return im_out
|
160 |
+
###################################
|
161 |
+
|
162 |
+
|
163 |
+
|
164 |
+
################ crypt #####################
|
165 |
+
|
166 |
+
def calculate_hash(data, hash_function: str = "sha256") -> str:
|
167 |
+
if type(data) == str:
|
168 |
+
data = bytearray(data, "utf-8")
|
169 |
+
if hash_function == "sha256":
|
170 |
+
h = SHA256.new()
|
171 |
+
h.update(data)
|
172 |
+
return h.hexdigest()
|
173 |
+
if hash_function == "ripemd160":
|
174 |
+
h = RIPEMD160.new()
|
175 |
+
h.update(data)
|
176 |
+
return h.hexdigest()
|
177 |
+
|
178 |
+
def generate_keys():
|
179 |
+
secret_code="SECRET PASSWORD"
|
180 |
+
key = RSA.generate(2048)
|
181 |
+
#private_key = key.export_key('PEM')
|
182 |
+
private_key = key.export_key(passphrase=secret_code, pkcs=8,
|
183 |
+
protection="scryptAndAES128-CBC")
|
184 |
+
print(f'private_key:: {private_key}')
|
185 |
+
|
186 |
+
file_out_priv = open("private.pem", "wb")
|
187 |
+
file_out_priv.write(private_key)
|
188 |
+
file_out_priv.close()
|
189 |
+
|
190 |
+
public_key = key.publickey().export_key('PEM')
|
191 |
+
file_out_pub = open("receiver.pem", "wb")
|
192 |
+
file_out_pub.write(public_key)
|
193 |
+
file_out_pub.close()
|
194 |
+
|
195 |
+
|
196 |
+
hash_1 = calculate_hash(public_key, hash_function="sha256")
|
197 |
+
hash_2 = calculate_hash(hash_1, hash_function="ripemd160")
|
198 |
+
address = base58.b58encode(hash_2)
|
199 |
+
address_im=qr.make_qr(txt=address)
|
200 |
+
add_label = str(address)
|
201 |
+
add_label = add_label.strip("b").strip("'")
|
202 |
+
address_im = overlay.textover(address_im, "Wallet",add_label)
|
203 |
+
address_im.save("address_im.png")
|
204 |
+
#qr_link="test"
|
205 |
+
address_im = "address_im.png"
|
206 |
+
private_key_im = overlay.textover("private_key.png", "Key",add_label)
|
207 |
+
private_key_im.save("private_key_im.png")
|
208 |
+
priv_key = conv_im("private_key_im.png",data=private_key)
|
209 |
+
|
210 |
+
pub_key = conv_im("address_im.png",data=public_key)
|
211 |
+
|
212 |
+
return public_key,private_key,address_im,address,priv_key,pub_key
|
213 |
+
|
214 |
+
|
215 |
+
def encrypt_text(data,pub_im,priv_im,address):
|
216 |
+
pub_key = decode(pub_im)
|
217 |
+
data = data.encode("utf-8")
|
218 |
+
recipient_key = RSA.import_key(pub_key)
|
219 |
+
session_key = get_random_bytes(16)
|
220 |
+
|
221 |
+
# Encrypt the session key with the public RSA key
|
222 |
+
cipher_rsa = PKCS1_OAEP.new(recipient_key)
|
223 |
+
enc_session_key = cipher_rsa.encrypt(session_key)
|
224 |
+
|
225 |
+
# Encrypt the data with the AES session key
|
226 |
+
cipher_aes = AES.new(session_key, AES.MODE_EAX)
|
227 |
+
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
|
228 |
+
|
229 |
+
file_out = open("encrypted_data.bin", "wb")
|
230 |
+
|
231 |
+
[ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
|
232 |
+
file_out.close()
|
233 |
+
doc_name = "encrypted_data.bin"
|
234 |
+
with open(doc_name, "rb") as file:
|
235 |
+
file_data =(file.read())
|
236 |
+
print (f'file_data::{file_data}')
|
237 |
+
qr_link="test"
|
238 |
+
#trans_im1.save("trans_im.png")
|
239 |
+
hash_1 = calculate_hash(pub_key, hash_function="sha256")
|
240 |
+
hash_2 = calculate_hash(hash_1, hash_function="ripemd160")
|
241 |
+
address = base58.b58encode(hash_2)
|
242 |
+
add_label = str(address)
|
243 |
+
add_label = add_label.strip("b").strip("'")
|
244 |
+
trans_im1=qr.make_qr(txt=address, color_b="#ECFD08")
|
245 |
+
private_key_im = overlay.textover(trans_im1, "Transaction",add_label)
|
246 |
+
private_key_im.save("private_key_im.png")
|
247 |
+
enc_qr = conv_im("private_key_im.png",data=file_data)
|
248 |
+
file.close()
|
249 |
+
return str(file_data),enc_qr
|
250 |
+
|
251 |
+
def decrypt_text(im,in2):
|
252 |
+
enc_in = decode(im)
|
253 |
+
secret_code="SECRET PASSWORD"
|
254 |
+
#private_key = RSA.import_key(open("private.pem").read())
|
255 |
+
priv_key = decode(in2)
|
256 |
+
print(f'priv_key:: {priv_key}')
|
257 |
+
private_key = RSA.import_key(priv_key,passphrase=secret_code)
|
258 |
+
print(f'private_key:: {private_key}')
|
259 |
+
enc_session_key = enc_in[:private_key.size_in_bytes()]
|
260 |
+
end1 = private_key.size_in_bytes()+16
|
261 |
+
nonce = enc_in[private_key.size_in_bytes():end1]
|
262 |
+
start1=end1+1
|
263 |
+
end2 = private_key.size_in_bytes()+32
|
264 |
+
start2=end2+1
|
265 |
+
tag = enc_in[end1:end2]
|
266 |
+
ciphertext = enc_in[end2:]
|
267 |
+
print (f'enc_session_key::{enc_session_key}')
|
268 |
+
print (f'nonce::{nonce}')
|
269 |
+
print (f'tag::{tag}')
|
270 |
+
print (f'ciphertext::{ciphertext}')
|
271 |
+
|
272 |
+
# Decrypt the session key with the private RSA key
|
273 |
+
cipher_rsa = PKCS1_OAEP.new(private_key)
|
274 |
+
session_key = cipher_rsa.decrypt(enc_session_key)
|
275 |
+
|
276 |
+
# Decrypt the data with the AES session key
|
277 |
+
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
|
278 |
+
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
|
279 |
+
return(data.decode("utf-8"))
|
280 |
+
|