-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
495 lines (433 loc) · 14.9 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
from flask import Flask, jsonify, request, make_response, send_file
from flask.helpers import send_from_directory
# from cryptogy.gammapentagonal import GammaPentagonalCipher
from flask_cors import CORS
import logging
import cryptogy
from cryptogy.hill_cipher import HillCipher, HillCryptAnalizer
from cryptogy.mv import MVCipher
from cryptogy.stream_ciphers import AutokeyCipher, AutokeyCryptAnalizer, StreamCipher
import cryptogy.des
from cryptogy.des import SDESCipher, DESCipher, TripleDESCipher
from cryptogy.dss import DSS_Signature
import cryptogy.aes
from cryptogy.aes import AESCipher
import cryptogy.rsa
from cryptogy.rsa import RSACipher
import utils
from base64 import encode, encodebytes
import io
from PIL import Image
from utils import images_key
import numpy as np
import os
import gc
logging.basicConfig(
filename="app.log", filemode="w", format="%(name)s - %(levelname)s - %(message)s"
)
app = Flask(__name__)
cors = CORS(app)
app.config["CORS_HEADERS"] = "Content-Type"
def get_response_image(image_path):
pil_img = Image.open(image_path, mode="r") # reads the PIL image
byte_arr = io.BytesIO()
pil_img.save(byte_arr, format="PNG") # convert the PIL image to byte array
encoded_img = encodebytes(byte_arr.getvalue()).decode("ascii") # encode as base64
return encoded_img
@app.route("/<path:path>", methods=["GET"])
def static_proxy(path):
gc.collect()
return send_from_directory("./static", path)
# Main page.
@app.route("/", methods=["GET"])
def root():
"""
Return the frontend of the application.
"""
gc.collect()
return send_from_directory("./static", "index.html")
# Main page.
@app.route("/classic", methods=["GET"])
def classic():
"""
Return the frontend of the application.
"""
gc.collect()
return send_from_directory("./static", "index.html")
# Main page.
@app.route("/block", methods=["GET"])
def block():
"""
Return the frontend of the application.
"""
gc.collect()
return send_from_directory("./static", "index.html")
# Main page.
@app.route("/gamma-pentagonal", methods=["GET"])
def gamma_pentagonal():
"""
Return the frontend of the application.
"""
gc.collect()
return send_from_directory("./static", "index.html")
# Main page.
@app.route("/publickey", methods=["GET"])
def publickey():
"""
Return the frontend of the application.
"""
gc.collect()
return send_from_directory("./static", "index.html")
# Main page.
@app.route("/dss", methods=["GET"])
def dss():
"""
Return the frontend of the application.
"""
gc.collect()
return send_from_directory("./static", "index.html")
@app.route("/api/generate_random_key", methods=["POST"])
def generate_random_key():
data = request.get_json()
if data == None:
data = request.values
print("CIPHER: ", data["cipher"])
cipher = utils.get_cipher(data)
random_key = cipher.generateRandomKey()
print(random_key)
if isinstance(cipher, RSACipher):
random_key = list(random_key)
random_key[0] = str(random_key[0])
random_key[1] = str(random_key[1])
# print(random_key)
# print(random_key)
if isinstance(cipher, HillCipher):
random_key = utils.format_darray(random_key)
elif (
isinstance(cipher, SDESCipher)
or isinstance(cipher, DESCipher)
or isinstance(cipher, TripleDESCipher)
):
random_key = utils.format_list(random_key)
elif isinstance(cipher, AESCipher):
random_key = random_key.hex()
return jsonify({"random_key": random_key}), 200
@app.route("/api/encrypt", methods=["POST"])
def encrypt():
data = request.get_json()
if data == None:
data = request.values
cleartext = data["cleartext"].lower().replace(" ", "")
if data["cipher"] == "aes":
key = bytes.fromhex(data["key"])
else:
key = utils.format_key(data["key"])
cipher = utils.get_cipher(data)
cipher.setKey(key)
if data["cipher"] not in ["aes", "sdes", "des", "rsa", "elgamal", "rabin"]:
encode_text = cipher.encode(cleartext)
elif data["cipher"] == "rsa" or data["cipher"] == "rabin":
pNumber = int(key[0])
qNumber = int(key[1])
encode_text = cipher.encode(pNumber, qNumber, cleartext)
encode_text = list(map(lambda x: str(x), encode_text))
elif data["cipher"] == "elgamal":
a = int(key[0])
b = int(key[1])
p = int(key[2])
generator = (int(key[3]), int(key[4]))
alpha = int(key[5])
k = int(key[6])
cipher = MVCipher()
cipher.setParams(a, b, p, generator)
message = tuple(map(lambda x: int(x), cleartext.split(",")))
encode_text = cipher.encode(message, alpha, k)
elif data["cipher"] in ["sdes", "des"]:
if data["initialPermutation"] != "":
iv = utils.format_str_to_list(data["initialPermutation"])
# print(iv)
cipher.setInitialPermutation(iv)
encode_text = cipher.encode(cleartext)
else:
encryptionMode = data["encryptionMode"]
iv = bytes.fromhex(data["initialPermutation"])
encode_text = cryptogy.aes.encrypt_text(key, iv, encryptionMode, cleartext)
if isinstance(cipher, AutokeyCipher):
gc.collect()
return (
jsonify({"ciphertext": encode_text[0], "key_stream": encode_text[1]}),
200,
)
elif (
isinstance(cipher, SDESCipher)
or isinstance(cipher, DESCipher)
or isinstance(cipher, TripleDESCipher)
):
# print("Encrypt schedule: ")
# print(encode_text[1])
string = ""
for list_ in encode_text[2]: # schedule
string += utils.format_list(list_) + ";"
return jsonify(
{
"ciphertext": encode_text[0],
"permutation": utils.format_list(encode_text[1]),
"schedule": string,
}
)
elif isinstance(cipher, AESCipher):
ciphertext = encode_text[0].hex()
iv = encode_text[1].hex()
return jsonify({"ciphertext": ciphertext, "initialPermutation": iv}), 200
else:
return jsonify({"ciphertext": encode_text}), 200
@app.route("/api/decrypt", methods=["POST"])
def decrypt():
data = request.get_json()
if data == None:
data = request.values
ciphertext = data["ciphertext"]
cipher = utils.get_cipher(data)
if data["cipher"] == "aes":
ciphertext = bytes.fromhex(data["ciphertext"])
key = bytes.fromhex(data["key"])
else:
key = utils.format_key(data["key"])
if isinstance(cipher, AutokeyCipher):
key_stream = utils.format_key(data["keyStream"])
cleartext = cipher.decode(key_stream, ciphertext)
elif (
isinstance(cipher, SDESCipher)
or isinstance(cipher, DESCipher)
or isinstance(cipher, TripleDESCipher)
):
permutation = utils.format_key(data["initialPermutation"], return_np=False)
schedule = utils.format_key(data["schedule"], return_np=False)
encryptionMode = data["encryptionMode"]
cipher.setEncryptionMode(encryptionMode)
cleartext = cipher.decode(permutation, schedule, ciphertext)[0]
elif isinstance(cipher, AESCipher):
cipher.setKey(key)
encryptionMode = data["encryptionMode"]
iv = bytes.fromhex(data["initialPermutation"])
cleartext = cryptogy.aes.decrypt_text(key, iv, encryptionMode, ciphertext)
cleartext = cleartext.decode("utf-8")
elif isinstance(cipher, RSACipher):
print("hola mundo")
pNumber = int(key[0])
qNumber = int(key[1])
for i in range(len(ciphertext)):
ciphertext[i] = int(ciphertext[i])
print("DECODIFICAR LO SIGUIENTE")
print(ciphertext)
print(pNumber)
print(qNumber)
cleartext = cipher.decode(pNumber, qNumber, ciphertext)
elif isinstance(cipher, MVCipher):
a = int(key[0])
b = int(key[1])
p = int(key[2])
generator = (int(key[3]), int(key[4]))
alpha = int(key[5])
k = int(key[6])
cipher = MVCipher()
cipher.setParams(a, b, p, generator)
cleartext = str(cipher.decode(ciphertext, alpha))[1:-1]
else:
cipher.setKey(key)
cleartext = cipher.decode(ciphertext)
gc.collect()
return jsonify({"cleartext": cleartext}), 200
@app.route("/api/signature", methods=["POST"])
def signature():
print("SIGNATURE: ,")
data = request.get_json()
if data == None:
data = request.values
cleartext = data["cleartext"]
dss = DSS_Signature()
cleartext = bytes(cleartext, encoding="utf-8")
# print("CLEARTEXT: ")
# print(cleartext)
publickey, signature = dss.getSignature(cleartext)
# print(signature, type(signature))
signature = signature.decode("ISO-8859-1").encode("utf-8").decode("utf-8")
return jsonify({"signature": signature})
@app.route("/api/analyze", methods=["POST"])
def analyze():
data = request.get_json()
if data == None:
data = request.values
ciphertext = data["ciphertext"]
analyzer = utils.get_analyzer(data)
if isinstance(analyzer, AutokeyCryptAnalizer):
cleartext = data["cleartext"]
try:
results = analyzer.breakCipher(cleartext, ciphertext)
except Exception as e:
# print(str(e))
gc.collect()
return jsonify({"error": str(e)}), 400
elif isinstance(analyzer, HillCryptAnalizer):
cleartext = data["cleartext"]
numPartitions = int(data["numPartitions"])
try:
results = analyzer.breakCipher(ciphertext, cleartext, numPartitions)
except Exception as e:
gc.collect()
return jsonify({"error": str(e)}), 400
else:
try:
results = analyzer.breakCipher(ciphertext)
except Exception as e:
gc.collect()
return jsonify({"error": str(e)}), 400
gc.collect()
return jsonify({"cleartext": results}), 200
@app.route("/api/encrypt_image", methods=["POST", "GET"])
def encrypt_image():
# print("ENCRYPT IMAGE")
from utils import images_key
data = request.values
cipher = data["cipher"]
img = request.files.getlist("files")[0]
img.save("./images/raw_img.png")
if cipher == "hill" or cipher == "permutation":
img = HillCipher.imagToMat(img, resize=32)
cipher = HillCipher(32, key=images_key, force_key=True)
new_img = cipher.encode_image(img)
new_img.save("./images/encrypt_temp.png")
file = send_from_directory(
"./images",
mimetype="image/png",
path="encrypt_temp.png",
as_attachment=False,
max_age=0,
)
elif cipher == "aes":
# key = bytes.fromhex(data["key"])
# iv = bytes.fromhex(data["initialPermutation"])
key = b"Sixteen byte key"
iv = b"0000000000000000"
encryptionMode = data["encryptionMode"]
route = "./images/raw_img.png"
res = cryptogy.aes.encrypt_image(
key, iv, encryptionMode, route, filename="./images/encrypt_temp.png"
)
file = send_from_directory(
"./images",
mimetype="image/png",
path="encrypt_temp.png",
as_attachment=False,
max_age=0,
)
elif cipher == "des" or "sdes" or "3des":
# key = b"Sixteen byte key"
# iv = b"0000000000000000"
key = b"\x97t\x84\xdb \x8b\xb2b"
iv = b"Uh:d2HqF"
encryptionMode = data["encryptionMode"]
route = "./images/raw_img.png"
res = cryptogy.des.encrypt_image(
key, iv, encryptionMode, route, filename="./images/encrypt_temp.png"
)
file = send_from_directory(
"./images",
mimetype="image/png",
path="encrypt_temp.png",
as_attachment=False,
max_age=0,
)
gc.collect()
return file
@app.route("/api/decrypt_image", methods=["POST", "GET"])
def decrypt_image():
from utils import images_inv_key
data = request.values
# print("DATAA DECRYPT!!")
# print(data)
cipher = data["cipher"]
# img = request.files.getlist("files")[0]
# image = "./images/encrypt_temp.png"
img = request.files.getlist("files")[0]
img.save("./images/encrypted_raw_img.png")
# img = open(image, "rb")
if cipher == "hill" or cipher == "permutation":
img = HillCipher.imagToMat(img, resize=32)
prev = Image.fromarray(img)
prev.save("./images/previous_encrypt.png")
cipher = HillCipher(32, key=images_key, force_key=True)
new_img = cipher.decode_image(img, key_inv=images_inv_key)
new_img = new_img.convert("L")
new_img.save("./images/decrypt_temp.png")
file = send_from_directory(
"./images",
mimetype="image/jpg",
path="decrypt_temp.png",
as_attachment=False,
max_age=0,
)
elif cipher == "aes":
# key = bytes.fromhex(data["key"])
# iv = bytes.fromhex(data["initialPermutation"])
key = b"Sixteen byte key"
iv = b"0000000000000000"
encryptionMode = data["encryptionMode"]
route = "./images/encrypted_raw_img.png"
res = cryptogy.aes.decrypt_image(
key, iv, encryptionMode, route, filename="./images/decrypt_temp.png"
)
gc.collect()
file = send_from_directory(
"./images",
mimetype="image/jpg",
path="decrypt_temp.png",
as_attachment=False,
max_age=0,
)
elif cipher == "des" or "sdes" or "3des":
# key = b"Sixteen byte key"
# iv = b"0000000000000000"
key = b"\x97t\x84\xdb \x8b\xb2b"
iv = b"Uh:d2HqF"
encryptionMode = data["encryptionMode"]
route = "./images/encrypted_raw_img.png"
res = cryptogy.des.decrypt_image(
key, iv, encryptionMode, route, filename="./images/decrypt_temp.png"
)
gc.collect()
file = send_from_directory(
"./images",
mimetype="image/jpg",
path="decrypt_temp.png",
as_attachment=False,
max_age=0,
)
gc.collect()
return file
@app.route("/api/change_graph", methods=["POST"])
def change_graph():
# print("1234")
data = request.get_json()
if data == None:
data = request.values
cipher = utils.get_cipher(data)
cipher.changeGraph()
gc.collect()
return jsonify({"message": "ok"})
@app.route("/api/show_graph", methods=["POST", "GET"])
def show_graph():
data = request.values
key = data["key"]
res = cryptogy.gammapentagonal.showGraph(key, filename="./images/graph_temp.png")
file = send_from_directory(
"./images",
mimetype="image/jpg",
path="graph_temp.png",
as_attachment=False,
max_age=0,
)
gc.collect()
return file
if __name__ == "__main__":
app.run(port=5000, debug=True)