-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvigenereCipher.py
580 lines (410 loc) · 19.6 KB
/
vigenereCipher.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# Vigenere Cipher Algorithm
"""
Padlock Encryption Software
Copyright 2019
Created by: Suraj Kothari
For A-level Computer Science
at Woodhouse College.
"""
import imageCrypt
import base64
import itertools
import os
import time
guide_data = {}
def getShiftValuesForImage(passKey):
""" Returns a list of ASCII values for each character in the passkey for image encryption and decryption """
return [ord(char) for char in passKey]
def getPassKeyString_classic(text, passKey):
# A generator cycling through the characters in the pass key
passKeyCycle = itertools.cycle(passKey)
passKeyString = ""
for i, t in enumerate(text, 1):
if t.isalpha():
nextKey = next(passKeyCycle) # Gets the next key
passKeyString += nextKey
# If text is smaller than 5, then not all keywords are needed for guide data
if len(text) <= 5:
# Inititialises all keywords to a blank value
guide_data['pks_demo_t1'] = ""
guide_data['pks_demo_k1'] = ""
guide_data['pks_demo_t2'] = ""
guide_data['pks_demo_k2'] = ""
guide_data['pks_demo_t3'] = ""
guide_data['pks_demo_k3'] = ""
guide_data['pks_demo_t4'] = ""
guide_data['pks_demo_k4'] = ""
guide_data['pks_demo_t5'] = ""
guide_data['pks_demo_k5'] = ""
if i == 1:
guide_data['pks_demo_t1'] = t
guide_data['pks_demo_k1'] = nextKey
elif i == 2:
guide_data['pks_demo_t2'] = t
guide_data['pks_demo_k2'] = nextKey
elif i == 3:
guide_data['pks_demo_t3'] = t
guide_data['pks_demo_k3'] = nextKey
elif i == 4:
guide_data['pks_demo_t4'] = t
guide_data['pks_demo_k4'] = nextKey
elif i == 5:
guide_data['pks_demo_t5'] = t
guide_data['pks_demo_k5'] = nextKey
else:
# Add on any special characters WITHOUT incrementing the key character
passKeyString += t
if i == 1:
guide_data['pks_demo_t1'] = t
guide_data['pks_demo_k1'] = t
elif i == 2:
guide_data['pks_demo_t2'] = t
guide_data['pks_demo_k2'] = t
elif i == 3:
guide_data['pks_demo_t3'] = t
guide_data['pks_demo_k3'] = t
elif i == 4:
guide_data['pks_demo_t4'] = t
guide_data['pks_demo_k4'] = t
elif i == 5:
guide_data['pks_demo_t5'] = t
guide_data['pks_demo_k5'] = t
guide_data['pks'] = passKeyString
return passKeyString
def getPassKeyString_ASCII(text, passKey):
"""
Returns the special pass-key-string.
This section calculates the pass-key-string to match the message length.
Let the passkey be: king
Let the message be: Hide in the forest.
The pass-key-string length should match the length of the message like this:
k i n g k i n g k i n g k i n g k i
H i d e i n t h e f o r e s t
Here, the passkey (king) is repeated 4 whole times.
This is the result of: len(message) DIV len(passkey).
The (2) extra characters to fill the rest of the message are: k i
The (2) comes from the result of: len(message) MOD len(passkey).
The pass-key-string is the concatenation of the passkey repeated
the (whole number of times + the remaining characters):
("king" * 4) + ki
(kingkingkingkingki)
"""
# Gets the whole number of times the pass key is repeated
repeatedNum = (len(text) // len(passKey))
# Gets the remaining characters
extraChars = passKey[0:(len(text) % len(passKey))]
"""
Repeats the original passkey the correct number of times
and then concatenates both parts to form the pass-key-string.
"""
passKeyString = (passKey * repeatedNum) + extraChars
guide_data['pks_n'] = repeatedNum
guide_data['pks_r'] = extraChars
guide_data['pks'] = passKeyString
return passKeyString
def encryptMessage_CLASSIC(plaintext, passKey):
""" Encrypts a plaintext with the passkey in CLASSIC mode """
guide_data['fc'] = 'Encryption'
guide_data['txt'] = plaintext
guide_data['key'] = passKey
cipherText = ""
passKeyString = getPassKeyString_classic(text=plaintext, passKey=passKey)
alphabet = "abcdefghijklmnopqrstuvwxyz"
# Iterates through the pass-key-string and the plaintext simultaneously
for x, (keyChar, plaintextChar) in enumerate(list(zip(passKeyString, plaintext))):
if plaintextChar.lower() in alphabet:
if plaintextChar.isupper():
# Gets the letter position for each letter in the pass key string
passKeyString_letter = alphabet.index(keyChar.lower()) + 1
# Gets the letter position of each plain text character
character_letter = alphabet.index(plaintextChar.lower()) + 1
# Gets new position of encrypted character in the alphabet
shiftedValue = (((character_letter - 1) + (passKeyString_letter - 1)) % 26) + 1
# Gets the character at this new position
newChar = alphabet[shiftedValue - 1]
# We only need to save the first shifted value and new character
if x == 0:
guide_data['sv'] = shiftedValue
guide_data['nc'] = newChar
# Concatenates each encrypted character onto the plaintext string
cipherText += newChar.upper()
else:
# Gets the letter position for each letter in the pass key string
passKeyString_letter = alphabet.index(keyChar.lower()) + 1
# Gets the letter position of each plain text character
character_letter = alphabet.index(plaintextChar.lower()) + 1
# Gets new position of encrypted character in the alphabet
shiftedValue = (((character_letter - 1) + (passKeyString_letter - 1)) % 26) + 1
# Gets the character at this new position
newChar = alphabet[shiftedValue - 1]
# We only need to save the first shifted value and new character
if x == 0:
guide_data['sv'] = shiftedValue
guide_data['nc'] = newChar
# Concatenates each encrypted character onto the plaintext string
cipherText += newChar
else:
# Any non-alphabetical character is just added
cipherText += plaintextChar
guide_data['f_txt'] = cipherText
return cipherText
def encryptMessage_ASCII(plaintext, passKey):
""" Encrypts a plaintext with the passkey in ASCII mode """
guide_data['fc'] = 'Encryption'
guide_data['txt'] = plaintext
guide_data['key'] = passKey
cipherText = ""
passKeyString = getPassKeyString_ASCII(text=plaintext, passKey=passKey)
# Iterates through the pass-key-string and the plaintext simultaneously
for x, (keyChar, plaintextChar) in enumerate(list(zip(passKeyString, plaintext))):
# Gets the ASCII value for each character in the pass key string
passKeyString_ASCII = ord(keyChar)
# Gets ASCII value of each plain text character
character_ASCII = ord(plaintextChar)
# Gets new position of encrypted character in ASCII
shiftedValue = (((character_ASCII - 32) + (passKeyString_ASCII - 32)) % 95) + 32
# Gets the character at this new position
newChar = chr(shiftedValue)
# We only need to save the first shifted value and new character
if x == 0:
guide_data['sv'] = shiftedValue
guide_data['nc'] = newChar
# Concatenates each encrypted character onto the plaintext string
cipherText += newChar
guide_data['f_txt'] = cipherText
return cipherText
def decryptMessage_CLASSIC(ciphertext, passKey):
""" Decrypts a ciphertext with the passkey in CLASSIC mode """
guide_data['fc'] = 'Decryption'
guide_data['txt'] = ciphertext
guide_data['key'] = passKey
plainText = ""
passKeyString = getPassKeyString_classic(text=ciphertext, passKey=passKey)
alphabet = "abcdefghijklmnopqrstuvwxyz"
# Iterates through the pass-key-string and the plaintext simultaneously
for x, (keyChar, ciphertextChar) in enumerate(list(zip(passKeyString, ciphertext))):
if ciphertextChar.lower() in alphabet:
if ciphertextChar.isupper():
# Gets the letter position for each letter in the pass key string
passKeyString_letter = alphabet.index(keyChar.lower()) + 1
# Gets the letter position of each plain text character
character_letter = alphabet.index(ciphertextChar.lower()) + 1
# Gets new position of encrypted character in the alphabet
shiftedValue = (((character_letter - 1) - (passKeyString_letter - 1)) % 26) + 1
# Gets the character at this new position
newChar = alphabet[shiftedValue - 1]
# We only need to save the first shifted value and new character
if x == 0:
guide_data['sv'] = shiftedValue
guide_data['nc'] = newChar
# Concatenates each encrypted character onto the plaintext string
plainText += newChar.upper()
else:
# Gets the letter position for each letter in the pass key string
passKeyString_letter = alphabet.index(keyChar.lower()) + 1
# Gets the letter position of each ciphertext character
character_letter = alphabet.index(ciphertextChar.lower()) + 1
# Gets new position of encrypted character in the alphabet
shiftedValue = (((character_letter - 1) - (passKeyString_letter - 1)) % 26) + 1
# Gets the character at this new position
newChar = alphabet[shiftedValue - 1]
# We only need to save the first shifted value and new character
if x == 0:
guide_data['sv'] = shiftedValue
guide_data['nc'] = newChar
# Concatenates each decrypted character onto the plaintext string
plainText += newChar
else:
# Any non-alphabetical character is just added
plainText += ciphertextChar
guide_data['f_txt'] = plainText
return plainText
def decryptMessage_ASCII(ciphertext, passKey):
""" Decrypts a ciphertext with the passkey in ASCII mode """
guide_data['fc'] = 'Decryption'
guide_data['txt'] = ciphertext
guide_data['key'] = passKey
plainText = ""
passKeyString = getPassKeyString_ASCII(text=ciphertext, passKey=passKey)
# Iterates through the pass-key-string and the ciphertext simultaneously
for x, (keyChar, ciphertextChar) in enumerate(list(zip(passKeyString, ciphertext))):
# Finds the ASCII value for each character in the pass key string
passKeyString_ASCII = ord(keyChar)
# Gets ASCII value of each ciphertext character.
character_ASCII = ord(ciphertextChar)
# Gets position of decrypted character in ASCII
shiftedValue = (((character_ASCII - 32) - (passKeyString_ASCII - 32)) % 95) + 32
# Gets the character at this position
newChar = chr(shiftedValue)
# We only need to save the first shifted value and new character
if x == 0:
guide_data['sv'] = shiftedValue
guide_data['nc'] = newChar
# Concatenates each decrypted character onto the ciphertext string
plainText += newChar
guide_data['f_txt'] = plainText
return plainText
def encryptFile(filename, filepath, passKey, cipherMode):
""" Encrypts the contents of a text file using base64 """
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], 'vigenere')
# 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 """
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], 'vigenere', 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], 'vigenere')
# 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], 'vigenere', 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()
shifts = getShiftValuesForImage(passKey=passKey)
encryptedData = imageCrypt.encrypt(filename=filename, filepath=filepath, shifts=shifts, cipherUsed="vigenere")
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 = getShiftValuesForImage(passKey=passKey)
decryptedData = imageCrypt.decrypt(filename=filename, filepath=filepath, shifts=shift, cipherUsed="vigenere")
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, 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, dataformat, ciphertext=ciphertext, filename=filename, filepath=filepath,
cipherMode=cipherMode)