-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
375 lines (275 loc) · 11.6 KB
/
main.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
import random
import re
import math
import string
# Define Reference Grid
values = [
["a", "b", "c", "d", "e", "f"],
["g", "h", "i", "j", "k", "l"],
["m", "n", "o", "p", "q", "r"],
["s", "t", "u", "v", "w", "x"],
["y", "z", "0", "1", "2", "3"],
["4", "5", "6", "7", "8", "9"]
]
myrows = ["1", "2", "1,1", "1,2", "2,1", "2,2"]
mycolumns = ["1", "2", "1,1", "1,2", "2,1", "2,2"]
# The encoded text for any character (alphabet or number) = row + column, joined together.
# Punctuation and spaces are ignored. So "abc" as per Reference grid = 111211,1.
# That is "a" = first row + first column = 11; "b" = first row + second column = 12 and "c" = first row + third column = 11,1 and so on.
# Define single row rotation
def rotaterow(myvalues, rowindex, rotation):
newrow = myvalues[rowindex]
rotatedrow = newrow[rotation % 6:] + newrow[:rotation % 6]
return rotatedrow
# Define single column rotation
def rotatecolumn(myvalues, columnindex, rotation):
newcolumn = [column[columnindex] for column in myvalues]
rotatedcolumn = newcolumn[rotation % 6:] + newcolumn[:rotation % 6]
return rotatedcolumn
# Find a particular character and return its cipher
def findme(mychar, myvalues):
cipher_string = ""
for rows in myvalues:
if mychar in rows:
cipher_string = (mycolumns[myvalues.index(rows)]) + (myrows[rows.index(mychar)])
return str(cipher_string)
# Read all decimal places of PI from the file
# and store as a string of 1 Million digits
with open("piDigits.txt", 'r') as f:
pidecimals = f.read()
f.close()
# Rotate the Reference grid in a random fashion
# Generate a Random Number
# Go to that position in pidecimlas
# Pick up N digits from that place in pidecimals
# such that the number of digits in the random number
# plus the number of digits from pidecimals = 12.
# If someone has the PiDigits file and the randomseed
# they will know which digits have been chosen.
# Now rotate the grid as per the combination of random number
# and the number of randomly chosen digits of Pi
def randomrotation():
myrandomseed = random.randint(1, len(pidecimals) - 12)
length_randomseed = len(str(myrandomseed))
deficit = 12 - length_randomseed
pistring = ""
for nmn in range(myrandomseed - 1, myrandomseed - 1 + deficit):
pistring += pidecimals[nmn]
rotationkey = (str(myrandomseed) + pistring)
rotatedrows = [rotaterow(values, ijk, int(rotationkey[ijk])) for ijk in range(0, 6)]
rotatedcolumns = [rotatecolumn(rotatedrows, ij - 6, int(rotationkey[ij])) for ij in range(6, 12)]
return rotatedcolumns, myrandomseed
# Rotate the reference grid if private key is supplied
def rotateme(privatekey):
rotatedrows = [rotaterow(values, ijk, int(privatekey[ijk])) for ijk in range(0, 6)]
rotatedcolumns = [rotatecolumn(rotatedrows, ij - 6, int(privatekey[ij])) for ij in range(6, 12)]
return rotatedcolumns
# Encoding Function as per Rotated Grid
def encode(myplain_text, rotatedgrid):
mycipher_text = ""
for letter in myplain_text:
dummy = findme(letter, rotatedgrid)
mycipher_text += dummy
return str(mycipher_text)
# Find User private key for Decoding
def findkey(userkey):
userkeylength = len(userkey)
userdeficit = 12 - userkeylength
pistring = ""
for nmm in range(int(userkey) - 1, int(userkey) - 1 + userdeficit):
pistring += pidecimals[nmm]
rotationkey = str(userkey) + pistring
return rotationkey
# Breakdown cipher text into chunks
def breakcode(usercipher):
decipher = re.compile(r'\w,\w|\w')
broken = decipher.findall(usercipher)
return broken
# Return number of characters in plain text
def countcipher(somecipher_text):
test = [breakcode(somecipher_text)]
return len(test[0]) / 2
# Create pairs of (column,row) from cipher_text
# Create the rotated grid based on private key
# Convert pairs into positions
def decode(somecipher_text, userkey):
test = []
flat_list = []
mygrid = creategrid(userkey)
test.append(breakcode(somecipher_text))
for sublist in test:
for item in sublist:
flat_list.append(item)
list_pairs = [flat_list[ii:ii + 2] for ii in range(0, len(flat_list), 2)]
columnpositions = [a[0] for a in list_pairs]
rowpositions = [a[1] for a in list_pairs]
columnindices = []
rowindices = []
for jj in range(len(columnpositions)):
for j in range(len(mycolumns)):
if columnpositions[jj] == mycolumns[j]:
columnindices.append(mycolumns.index(columnpositions[jj]))
for jj in range(len(rowpositions)):
for j in range(len(myrows)):
if rowpositions[jj] == myrows[j]:
rowindices.append(myrows.index(rowpositions[jj]))
my_decoded_text = ""
for m in range(len(rowindices)):
my_decoded_text += (mygrid[columnindices[m]][rowindices[m]])
return my_decoded_text
# Generate keys equal to number of characters in string
def genkeylist(inputstring):
pistring = ""
keyarray = []
myrandomseed = random.randint(1, len(pidecimals) - 12)
length_randomseed = len(str(myrandomseed))
deficit = 12 - length_randomseed
for n in range(myrandomseed - 1, myrandomseed - 1 + deficit):
pistring += pidecimals[n]
keystring = str(myrandomseed) + pistring
myfirstkey = int(keystring)
for char in range(len(inputstring)):
mynextkey = (myfirstkey ** (1 / 2)) % 1000000
mynextkey = mynextkey - int(mynextkey)
mynextkey = (str(mynextkey)[2:][:6])
keyarray.append(str(mynextkey))
myfirstkey = int(mynextkey)
return keystring, keyarray
# Create the grid from user private key
def creategrid(userkey):
thiskey = findkey(userkey)
rotatedgrid = rotateme(thiskey)
return rotatedgrid
# Remove spaces and punctuation from a string
def cleanstring(mystring):
mystring = mystring.replace(" ", "")
mystring = mystring.replace("\n", "")
mystring = re.sub("[^0-9a-zA-Z]+", "", mystring)
mystring = mystring.lower()
mystring = mystring.translate(str.maketrans('', '', string.punctuation))
return mystring
# Ensure number of rotations within a string
# is proportional to the length of string.
# This also limits number of keys if the message
# is too short.
def chopstring(some_str):
tempx = len(some_str) ** (1 / 4)
tempy = random.randint(0, 1)
if tempy == 1:
mynumkeys = math.ceil(tempx)
else:
mynumkeys = math.floor(tempx)
stringparts = math.ceil((len(some_str) / mynumkeys))
my_chunks = [some_str[k:k + stringparts] for k in range(0, len(some_str), stringparts)]
return my_chunks, mynumkeys
# Main Program
levelchoice = input("Type 1 for Easy, 2 for Moderate or 3 for Hard: ")
if levelchoice == "1":
print("You chose EASY level encryption: ")
choice = input("Write 1 to Encode or 0 to Decode: ")
if choice == "1":
plain_text = input("Enter message to be encoded: ")
plain_text = cleanstring(plain_text)
finalgrid, key = randomrotation()
print(f"The Encoded message is: {encode(plain_text, finalgrid)}")
print(f"Your Private Key is: {key}")
elif choice == "0":
cipher_text = input("Enter message to be decoded: ")
cipher_key = input("Enter Private Key: ")
print(f"The decoded message is: {decode(cipher_text, cipher_key)}")
else:
print("Invalid input.")
elif levelchoice == "2":
print("You chose MODERATE level encryption: ")
choice = input("Write 1 to Encode or 0 to Decode: ")
if choice == "1":
str_coded = []
keylist = []
chunklengths = []
codelist = []
str_final = ""
plain_text = input("Enter message to be encoded: ")
plain_text = cleanstring(plain_text)
chunks, numkeys = chopstring(plain_text)
for i in range(0, len(chunks)):
newgrid, randomseed = randomrotation()
str_coded.append(encode(chunks[i], newgrid) + ".")
keylist.append(str(randomseed))
codelist.append(str_coded[i])
chunklengths.append(len(str_coded[i]))
str_final += (codelist[i])
str_final.rstrip(".")
print(f"The Encoded message is : {str_final}")
print(f"Your Keys are: {keylist}")
elif choice == "0":
cipher_chunks = []
decoded_text = []
sent_str = ""
cipher_text = input("Enter message to be decoded: ")
cipher_text = cipher_text[:-1]
cipher_chunks.append(cipher_text.split("."))
for i in range(0, len(cipher_chunks[0])):
cipher_key = input(f"Enter Private Key number {i + 1}: ")
decoded_text.append(decode(cipher_chunks[0][i], cipher_key))
for i in decoded_text:
sent_str += str(i)
print(f"The Decoded message is : {sent_str}")
else:
print("Invalid input.")
elif levelchoice == "3":
print("You chose HARD level encryption.")
choice = input("Write 1 to Encode or 0 to Decode: ")
cipher_list = []
ciphertext = ""
if choice == "1":
plain_text = input("Enter message to be encoded: ")
plain_text = cleanstring(plain_text)
keyarray = genkeylist(plain_text)
for n in range(0, len(plain_text)):
newgengrid = creategrid(keyarray[1][n])
cipher_list.append(encode(plain_text[n], newgengrid))
ciphertext += str(cipher_list[n])
print(f"The Encoded message is: {ciphertext}")
print(f"Your Master Key is : {keyarray[0]}")
elif choice == "0":
actualstring = ""
keyarray = []
answerstring = []
codechunks = []
decoded_text = ""
gridlist = [[]]
codepairs = []
ciphertext = input("Enter message to be decoded: ")
actual_length = int(countcipher(ciphertext))
firstkey = input("Enter Master Key: ")
for i in range(0, actual_length):
nextkey = (int(firstkey) ** (1 / 2)) % 1000000
nextkey = nextkey - int(nextkey)
nextkey = (str(nextkey)[2:][:6])
keyarray.append(str(nextkey))
firstkey = int(nextkey)
for j in range(0, len(keyarray)):
gridlist.append(creategrid(keyarray[j]))
codechunks = breakcode(ciphertext)
for ll in range(0, len(codechunks), 2):
codepairs.append((codechunks[ll] + codechunks[ll + 1]))
listpairs = [codechunks[ii:ii + 2] for ii in range(0, len(codechunks), 2)]
columnpositions = [a[0] for a in listpairs]
rowpositions = [a[1] for a in listpairs]
columnindices = []
rowindices = []
for jj in range(len(columnpositions)):
for j in range(len(mycolumns)):
if columnpositions[jj] == mycolumns[j]:
columnindices.append(mycolumns.index(columnpositions[jj]))
for jj in range(len(rowpositions)):
for j in range(len(myrows)):
if rowpositions[jj] == myrows[j]:
rowindices.append(myrows.index(rowpositions[jj]))
for kk in range(0, actual_length):
decoded_text += (gridlist[kk + 1][columnindices[kk]][rowindices[kk]])
print(f"The Decoded message is : {decoded_text}")
else:
print("Invalid input.")
else:
print("Invalid input.")