-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesarCipher.py
478 lines (327 loc) · 14.5 KB
/
caesarCipher.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
# Caesar Cipher Algorithm
"""
Padlock Encryption Software
Copyright 2019
Created by: Suraj Kothari
For A-level Computer Science
at Woodhouse College.
"""
import imageCrypt
import base64
import os
import time
guide_data = {}
def getShiftKeyForImage(passKey):
""" Returns a shift key value from the pass key for image cipher """
ASCII_sum = 0
for chr in passKey:
ASCII_sum += ord(chr)
return ASCII_sum
def getShiftKey_CLASSIC(passKey):
""" Returns a shift key value from the pass key using the English Alphabet """
Letter_sum = 0
alphabet = "abcdefghijklmnopqrstuvwxyz"
for chr in passKey:
if chr.isalpha(): # Only alphabetical characters are used in the total
Letter_sum += alphabet.index(chr.lower()) + 1
"""
If the shift key value generated is a multiple of 26, then add 50 to it
as a shift of 26 would obtain the same character.
"""
guide_data['c_key'] = Letter_sum # Before
if Letter_sum % 26 == 0:
Letter_sum += 50
guide_data['f_c_key'] = Letter_sum # After
return Letter_sum
def getShiftKey_ASCII(passKey):
""" Returns a shift key value from the pass key using ASCII """
ASCII_sum = 0
for chr in passKey:
ASCII_sum += ord(chr)
"""
If the shift key value generated is a multiple of 95, then add 50 to it
as a shift of 95 would obtain the same character.
"""
guide_data['c_key'] = ASCII_sum # Before
if ASCII_sum % 95 == 0:
ASCII_sum += 50
guide_data['f_c_key'] = ASCII_sum # After
return ASCII_sum
def encryptMessage_CLASSIC(plaintext, passKey):
""" Encrypts a plaintext with a passkey in CLASSIC mode """
guide_data['fc'] = 'Encryption'
guide_data['txt'] = plaintext
guide_data['key'] = passKey
cipherText = ""
shift = getShiftKey_CLASSIC(passKey)
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i, Letter in enumerate(plaintext):
if Letter.isalpha():
if Letter.isupper():
letter_pos = alphabet.index(Letter.lower()) + 1
# Gets the new position of the encrypted letter in the alphabet
shiftedValue = (((letter_pos - 1) + shift) % 26) + 1
# We only need to save the first shifted value
if i == 0:
guide_data['sv'] = shiftedValue
# Gets the character at the new position.
newLetter = alphabet[shiftedValue - 1]
# Concatenates the encrypted character in uppercase onto the ciphertext
cipherText += newLetter.upper()
else:
letter_pos = alphabet.index(Letter.lower()) + 1
# Gets the new position of the encrypted letter in the alphabet
shiftedValue = (((letter_pos - 1) + shift) % 26) + 1
# We only need to save the first shifted value
if i == 0:
guide_data['sv'] = shiftedValue
# Gets the letter at the new position.
newLetter = alphabet[shiftedValue - 1]
# Concatenates the encrypted character in uppercase onto the ciphertext
cipherText += newLetter
else:
# Any non-alphabetical character is just added
cipherText += Letter
guide_data['f_txt'] = cipherText
return cipherText
def encryptMessage_ASCII(plaintext, passKey):
""" Encrypts a plaintext with a passkey in ASCII mode """
guide_data['fc'] = 'Encryption'
guide_data['txt'] = plaintext
guide_data['key'] = passKey
cipherText = ""
shift = getShiftKey_ASCII(passKey)
for i, CHR in enumerate(plaintext):
characterASCII = ord(CHR)
# Gets the new position of the encrypted character in ASCII
shiftedValue = (((characterASCII - 32) + shift) % 95) + 32
# We only need to save the first shifted value
if i == 0:
guide_data['sv'] = shiftedValue
# Gets the character at the new position.
newChar = chr(shiftedValue)
# Concatenates the encrypted character onto the ciphertext
cipherText += newChar
guide_data['f_txt'] = cipherText
return cipherText
def decryptMessage_CLASSIC(ciphertext, passKey):
""" Encrypts a plaintext with a passkey in CLASSIC mode """
guide_data['fc'] = 'Decryption'
guide_data['txt'] = ciphertext
guide_data['key'] = passKey
plainText = ""
shift = getShiftKey_CLASSIC(passKey)
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i, Letter in enumerate(ciphertext):
if Letter.isalpha():
if Letter.isupper():
letter_pos = alphabet.index(Letter.lower()) + 1
# Gets the new position of the encrypted letter in the alphabet
shiftedValue = (((letter_pos - 1) - shift) % 26) + 1
# We only need to save the first shifted value
if i == 0:
guide_data['sv'] = shiftedValue
# Gets the character at the new position.
newLetter = alphabet[shiftedValue - 1]
# Concatenates the encrypted character in uppercase onto the ciphertext
plainText += newLetter.upper()
else:
letter_pos = alphabet.index(Letter) + 1
# Gets the new position of the encrypted letter in the alphabet
shiftedValue = (((letter_pos - 1) - shift) % 26) + 1
# We only need to save the first shifted value
if i == 0:
guide_data['sv'] = shiftedValue
# Gets the letter at the new position.
newLetter = alphabet[shiftedValue - 1]
# Concatenates the encrypted character in uppercase onto the ciphertext
plainText += newLetter
else:
# Any non-alphabetical character is just added
plainText += Letter
guide_data['f_txt'] = plainText
return plainText
def decryptMessage_ASCII(ciphertext, passKey):
""" Decrypts a ciphertext with a passkey in ASCII mode """
guide_data['fc'] = 'Decryption'
guide_data['txt'] = ciphertext
guide_data['key'] = passKey
plainText = ""
shift = getShiftKey_ASCII(passKey)
for i, CHR in enumerate(ciphertext):
characterASCII = ord(CHR)
# Gets the new position of the decrypted character in ASCII
shiftedValue = (((characterASCII - 32) - shift) % 95) + 32
# We only need to save the first shifted value
if i == 0:
guide_data['sv'] = shiftedValue
# Gets the character at the new position.
newChar = chr(shiftedValue)
# Concatenates the decrypted character onto the plaintext
plainText += newChar
guide_data['f_txt'] = plainText
return plainText
def encryptFile(filename, filepath, passKey, cipherMode):
""" Encrypts the contents of a text file """
full_filename = filepath + "/" + filename
# Generates lines from the file
def getLines():
with open(full_filename) as f:
for line in f:
if line != "\n":
yield line.split("\n")[0]
else:
yield "\n"
# Generates encrypted data
def getEncryptedData():
# Gets file lines from generator
for L in getLines():
if L != "\n":
if cipherMode == "ASCII":
E = encryptMessage_ASCII(plaintext=L, passKey=passKey)
else:
E = encryptMessage_CLASSIC(plaintext=L, passKey=passKey)
else:
E = "\n"
yield E
newFilename = "{}/{}_{}_ENC.txt".format(filepath, filename[:-4], 'caesar')
# Writes each line of encrypted data
with open(newFilename, 'w') as f2:
for e in getEncryptedData():
if e != "\n":
f2.write(e + "\n")
else:
f2.write("\n")
return newFilename
def encryptFileBase64(filename, filepath, passKey):
""" Encrypts the contents of any file using base64 """
full_filename = filepath + "/" + filename
with open(full_filename, "rb") as f:
test = f.read()
"""
Converts the binary file contents to base64
and then formats it into ASCII form.
"""
encoded = base64.b64encode(test).decode("ascii")
Encrypted = encryptMessage_ASCII(plaintext=encoded, passKey=passKey)
extension = os.path.splitext(filename)[1]
eLength = len(extension)
newFilename = "{}/{}_{}_Base64_ENC{}".format(filepath, filename[:-eLength], 'caesar', extension)
# Converts the ASCII encryption into bytes form to write to new file
Encrypted = bytes(Encrypted, 'utf-8')
# Writes encrypted data to new file
with open(newFilename, 'wb') as f2:
f2.write(Encrypted)
return newFilename
def decryptFile(filename, filepath, passKey, cipherMode):
""" Decrypts the contents of a text file """
full_filename = filepath + "/" + filename
# Generates lines from the file
def getLines():
with open(full_filename) as f:
for line in f:
if line != "\n":
yield line.split("\n")[0]
else:
yield "\n"
# Generates decrypted data
def getDecryptedData():
# Gets file lines from generator
for L in getLines():
if L != "\n":
if cipherMode == "ASCII":
D = decryptMessage_ASCII(ciphertext=L, passKey=passKey)
else:
D = decryptMessage_CLASSIC(ciphertext=L, passKey=passKey)
else:
D = "\n"
yield D
if "ENC" in filename:
newFilename = "{}/{}".format(filepath, filename.replace("ENC", "DEC"))
else:
newFilename = "{}/{}_{}_DEC.txt".format(filepath, filename[:-4], 'caesar')
# Writes each line of encrypted data
with open(newFilename, 'w') as f2:
for d in getDecryptedData():
if d != "\n":
f2.write(d + "\n")
else:
f2.write("\n")
return newFilename
def decryptFileBase64(filename, filepath, passKey):
""" Decrypts the contents of any file using base64 """
full_filename = filepath + "/" + filename
with open(full_filename, "rb") as f:
# Formats the binary file into ASCII form.
content = f.read().decode("ascii")
Decrypted = decryptMessage_ASCII(ciphertext=content, passKey=passKey)
if "ENC" in filename:
newFilename = "{}/{}".format(filepath, filename.replace("ENC", "DEC"))
else:
extension = os.path.splitext(filename)[1]
eLength = len(extension)
newFilename = "{}/{}_{}_Base64_DEC{}".format(filepath, filename[:-eLength], 'caesar', extension)
# Converts the ASCII into bytes and then decodes it from base64 to original
decryptedContent = base64.b64decode(bytes(Decrypted, 'utf-8'))
# Creates decrypted file
with open(newFilename, 'wb') as f2:
f2.write(decryptedContent)
return newFilename
def encryptCheck(passKey, dataformat, cipherMode, plaintext=None, filename=None, filepath=None):
""" Organises how the different dataformats are encrypted """
if dataformat == "Messages":
if cipherMode == "ASCII":
encryptedData = encryptMessage_ASCII(plaintext=plaintext, passKey=passKey)
else:
encryptedData = encryptMessage_CLASSIC(plaintext=plaintext, passKey=passKey)
timeTaken = 0
elif dataformat == "Files":
if cipherMode == "Base64":
start = time.time()
encryptedData = encryptFileBase64(filename=filename, filepath=filepath, passKey=passKey)
end = time.time()
timeTaken = end - start
else:
start = time.time()
encryptedData = encryptFile(filename=filename, filepath=filepath, passKey=passKey, cipherMode=cipherMode)
end = time.time()
timeTaken = end - start
elif dataformat == "Images":
start = time.time()
shift = getShiftKeyForImage(passKey=passKey)
encryptedData = imageCrypt.encrypt(filename=filename, filepath=filepath, shifts=[shift], cipherUsed="caesar")
end = time.time()
timeTaken = end - start
return encryptedData, timeTaken
def decryptCheck(passKey, dataformat, cipherMode, ciphertext=None, filename=None, filepath=None):
""" Organises how the different dataformats are decrypted """
if dataformat == "Messages":
if cipherMode == "ASCII":
decryptedData = decryptMessage_ASCII(ciphertext=ciphertext, passKey=passKey)
else:
decryptedData = decryptMessage_CLASSIC(ciphertext=ciphertext, passKey=passKey)
timeTaken = 0
elif dataformat == "Files":
if cipherMode == "Base64":
start = time.time()
decryptedData = decryptFileBase64(filename=filename, filepath=filepath, passKey=passKey)
end = time.time()
timeTaken = end - start
else:
start = time.time()
decryptedData = decryptFile(filename=filename, filepath=filepath, passKey=passKey, cipherMode=cipherMode)
end = time.time()
timeTaken = end - start
elif dataformat == "Images":
start = time.time()
shift = getShiftKeyForImage(passKey=passKey)
decryptedData = imageCrypt.decrypt(filename=filename, filepath=filepath, shifts=[shift], cipherUsed="caesar")
end = time.time()
timeTaken = end - start
return decryptedData, timeTaken
def encrypt(passKey, dataformat, cipherMode, plaintext=None, filename=None, filepath=None):
return guide_data, encryptCheck(passKey=passKey, dataformat=dataformat, plaintext=plaintext,
filename=filename, filepath=filepath, cipherMode=cipherMode)
def decrypt(passKey, dataformat, cipherMode, ciphertext=None, filename=None, filepath=None):
return guide_data, decryptCheck(passKey=passKey, dataformat=dataformat, ciphertext=ciphertext,
filename=filename, filepath=filepath, cipherMode=cipherMode)