-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
394 lines (343 loc) · 16.6 KB
/
main.py
File metadata and controls
394 lines (343 loc) · 16.6 KB
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
import string as st
import os.path
from jnius import autoclass
from time import sleep
from android.permissions import request_permissions, Permission, check_permission
if not check_permission(Permission.WRITE_EXTERNAL_STORAGE) or not check_permission(Permission.READ_EXTERNAL_STORAGE):
request_permissions([Permission.WRITE_EXTERNAL_STORAGE,
Permission.READ_EXTERNAL_STORAGE])
sleep(5)
from kivy.config import Config
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.factory import Factory
from kivy.core.window import Window
Window.softinput_mode = 'below_target'
Config.set('kivy','pause_on_minimize', 1)
Config.set('kivy', 'exit_on_escape', 0)
allASCII = st.printable
theKey = '''Congue comprehensam eam id, utroque forensibus ad quo, pertinax sensibus dissentias vim at. Cu brute reprimique dissentiunt duo. Nullam platonem intellegam ea eam. Quo ei numquam qualisque consetetur, hinc mediocrem cu pri. Sea id paulo facilisis iracundia, sea ad civibus principes splendide, nam oportere contentiones signiferumque te. Te per semper intellegam. Ex vis unum elitr aperiam.
Pro at vidit vocibus, an laboramus reprimique efficiantur nec. His ignota vivendum recteque ut, ad eam paulo recteque. Nominavi iracundia quo te, eu sit viderer assentior? Sed at torquatos mediocritatem, diam quodsi et mea, mollis oblique scripserit ut per! Quando incorrupte pri ex, eruditi sententiae sit an! Eum ex natum consul dolorem!
Qui et accusamus definitiones, nam dicat quodsi et, liber iracundia has in. At mea eleifend petentium, eu quodsi nostrud reprimique vix. Per ludus prompta consequuntur et, ei sit ludus evertitur, atqui electram pri no. Discere percipitur ne pri! Delenit accusam facilisi eum no, in mea malis suscipit!
Mel alii purto viris ut, nostrum incorrupte vituperatoribus eu usu, eu petentium conclusionemque nec. Omnes honestatis an vis, eros posse eu est, no mei solet democritum interpretaris. Vix vero forensibus te, nostrum convenire adolescens eu vim! Vim te ignota vituperata consequuntur.
Error aperiri adversarium an est, vel id dicat denique. Ei nec ipsum mediocritatem, detraxit posidonium nec ea! Duis iuvaret admodum est eu, sea at partem periculis dignissim! Te mel ullum persequeris! Graeci eleifend vel ad, cu facilisi rationibus est. Pro ex facilis indoctum.
Ea vim nostrud suavitate, reque quando consequat eu vim. Nam mnesarchum complectitur cu, cum ne elit argumentum, fabulas ullamcorper vim ad. Vis tation graece eripuit ex, dolor vocent at usu. Veniam doctus legendos ea cum. In eos unum contentiones, ea duo sale harum soluta.
Amet modus ceteros eam an. Te amet esse mel, vim vero appareat ex. Pri ex modo scripta indoctum. Splendide sadipscing no pro, eripuit splendide te sed. Per legimus partiendo ei, erat epicuri ad vim! Veritus suscipiantur te vel.
Vidit natum delenit mea ad, ex pro maiorum platonem! Dolorem assueverit efficiantur eu vim. Eum id probatus disputationi, duo molestie qualisque no. Nam vide rationibus cu. Illum facer verterem ei has!
Et appetere complectitur quo. Ex magna utroque efficiendi pro. Sed ei partem persequeris, eu amet graecis vivendo ius. Enim suscipit efficiantur pro te, iisque argumentum quo ex! Ut noster impetus pri. Vix an sumo errem atomorum! Id tale error vel.
Alienum persecuti id eum, et eum enim autem molestie. Vulputate theophrastus delicatissimi ei his, ei pro odio putent pertinacia? Vim eu posse verear. Cu quo enim voluptatum appellantur, eos et volumus eligendi, alia legere menandri his ut! Cu pro etiam mazim petentium, est ex exerci scripserit.'''
defKey = theKey
theCode = {}
class CustPopup(Popup):
lbl_text = StringProperty('')
newkeyinput = StringProperty('')
class LoadDiag(BoxLayout):
dism = ObjectProperty(None)
load = ObjectProperty(None)
class SaveDiag(BoxLayout):
dism = ObjectProperty(None)
save = ObjectProperty(None)
text_input = ObjectProperty(None)
class RootBox(BoxLayout):
newkey_input = StringProperty('')
yesno_answer = StringProperty('')
temppath = StringProperty('')
tempfile = StringProperty('')
def show_load(self):
content = LoadDiag(dism = self.dismiss, load = self.load)
self.saveloadpop = Popup(title='Load file...', content=content, auto_dismiss=False)
self.saveloadpop.open()
def dismiss(self):
self.saveloadpop.dismiss()
def load(self, path, file):
if not file:
return
filename = file[0]
with open(filename) as filetoopen:
self.newkey_input = filetoopen.read()
self.dismiss()
def show_save(self):
content = SaveDiag(dism = self.dismiss, save = self.save)
self.saveloadpop = CustPopup(title='Enter a name for your backup file...', content=content, auto_dismiss=False)
self.saveloadpop.open()
def generic_yesno(self, tit, txt):
Factory.GenYesNo(title=tit, lbl_text=txt).open()
def save(self, path, file):
if not file:
return
validtext = st.ascii_letters + st.digits + '.-_ '
if any(char not in validtext for char in file):
Factory.GenericPop(title='Error',lbl_text='No special characters on the filename, please.').open()
return
if file in 'currentKey.txt' or file in 'defaultKey.txt':
Factory.GenericPop(title='Error',lbl_text='This file cannot be overwritten.').open()
return
oldkey_text = self.get_currentKeyFile()
filename = os.path.join(path, file)
self.temppath = path
self.tempfile = file
if os.path.exists(filename) and not self.yesno_answer:
self.generic_yesno(tit='Overwrite existing file?', txt='File already exists. Overwrite it?')
elif self.yesno_answer == 'no':
self.yesno_answer = ''
return
else:
self.yesno_answer = ''
if filename[-4:] != '.txt':
filename += '.txt'
with open(filename, 'w') as filetosave:
filetosave.write(oldkey_text)
self.dismiss()
def complete_Key(self, keystring):
'''
Returns a list of characters contained in the keystring so the program raises exceptions whenever you try to encode a message containing unmapped characters.
If some ascii characters are missing, they are added at the end of the string.
'''
origChars = set(keystring)
if any(char not in allASCII for char in origChars):
Factory.GenericPop(title='Error',lbl_text='Key contains non ASCII characters. Please enter a valid key.').open()
return
charsToAdd = [char for char in allASCII if char not in origChars]
stringToAdd = ''.join(charsToAdd)
finalKey = keystring + stringToAdd
return finalKey
def count_Frequency(self, keystring):
'''
Returns a sorted dictionary containing all ASCII characters and their frequencies in the keystring.
'''
completeKey = self.complete_Key(keystring)
freqDict = {}
for char in set(completeKey):
freqDict[char] = completeKey.count(char)
freqDict = self.sort_FreqDict(freqDict)
return freqDict
def sort_FreqDict(self, dic):
'''
Sorts chars dictionary by frequency. Ties are broken by 'alphabetical' order to ensure sorting consistency.
'''
if type(dic) is list:
toDict = dict(dic)
sortedDict = sorted(toDict.items(), key=lambda x: x[1], reverse=True)
else:
sortedDict = dict(sorted(dic.items(), key=lambda x: (x[1],x[0]), reverse=True))
return sortedDict
def create_Tree(self, dic):
'''
Creates the tree and nodes.
'''
pqueue = list(dic.items())
newNode = {}
for char in dic.keys(): #initializes leaf nodes
newNode[char] = []
while len(pqueue) > 1:
newKey = pqueue[-1][0] + pqueue[-2][0]
newFreq = pqueue[-1][1] + pqueue[-2][1]
reinsertedNode = (newKey,newFreq) #creates a node for reinsertion into pqueue
newNode[newKey] = [pqueue[-1][0], pqueue[-2][0]] #adds a pair of child nodes to each new node
pqueue = pqueue[:-2] #removes child nodes from pqueue
pqueue.append(reinsertedNode)
pqueue = self.sort_FreqDict(pqueue)
treeDict = newNode
return treeDict
def code_Gen(self, tree):
'''
Generates the code mapping and returns a dictionary
'''
root = max(tree.keys(),key=lambda x: len(x)) #gets the root key of the tree
codeDict = {}
for char in root:
code = ''
for child in tree.values():
if child:
if char in child[0]:
code = '0' + code
elif char in child[1]:
code = '1' + code
else:
continue
codeDict[char] = code
return codeDict
def zigzag_Split(self, seq):
'''
Splits a sequence into two, alternating the values. Expects a sorted list or dict as input.
'''
if type(seq) is dict:
seq = list(seq.items())
dic1, dic2 = seq[::2], seq[1::2]
dic1, dic2 = dict(dic1), dict(dic2)
return dic1, dic2
else:
return seq[::2], seq[1::2]
def map_Code(self, keystring):
'''
Puts all the above functions into one box. Returns the code map.
The frequency dictionary is split into 4 smaller dictionaries. Generates cleaner tree and shorter codes.
'''
freqDict = self.count_Frequency(keystring)
freq0, freq1 = self.zigzag_Split(freqDict)
freq00, freq01 = self.zigzag_Split(freq0)
freq10, freq11 = self.zigzag_Split(freq1)
tree00, tree01, tree10, tree11 = self.create_Tree(freq00), self.create_Tree(freq01), self.create_Tree(freq10), self.create_Tree(freq11)
code00, code01, code10, code11 = self.code_Gen(tree00), self.code_Gen(tree01), self.code_Gen(tree10), self.code_Gen(tree11)
for k, v in code00.items():
code00[k] = '00'+v
for k, v in code01.items():
code01[k] = '01'+v
for k, v in code10.items():
code10[k] = '10'+v
for k, v in code11.items():
code11[k] = '11'+v
mergedCode = {**code00, **code01, **code10, **code11}
return mergedCode
def encode_Text(self, text, codedict):
'''
Encodes a given text using code map generated by code_Gen (or map_Code)
'''
encText = ''
for char in text:
try:
encText += codedict[char]
except KeyError:
print('Only ASCII characters are accepted for now')
return
return encText
def decode_Text(self, text, codedict):
'''
Decodes a previously encoded text provided the both encryption and decryption used the right key.
'''
text = text.strip()
if any(char not in '01' for char in text):
print('Error: expected string of 0s and 1s.')
return
reversedDict = {v:k for k,v in codedict.items()}
decText = ''
fullCharCode = ''
for digit in text:
fullCharCode += digit
try:
decText += reversedDict[fullCharCode]
fullCharCode = ''
except KeyError:
continue
return decText
def enc_Button(self):
'''
Callback for encode button.
'''
toencode = self.ids.inputBox.text
try:
enctext = self.encode_Text(toencode,theCode)
self.ids.outputBox.ids.ti.text = enctext
except:
Factory.GenericPop(title='Error',lbl_text='Only printable ASCII characters are accepted.').open()
return
return
def dec_Button(self):
'''
Callback for decode button.
'''
todecode = self.ids.outputBox.text
try:
dectext = self.decode_Text(todecode,theCode)
self.ids.inputBox.ids.ti.text = dectext
except:
Factory.GenericPop(title='Error',lbl_text='Only 0s and 1s are accepted.').open()
return
return
def set_currentKeyFile(self, keystring):
'''
Write the new key to the currentKey.txt file, so the program remembers it next time.
'''
file_path = os.path.join(data_dir, 'currentKey.txt')
currentKeyFile = open(file_path, 'w')
currentKeyFile.write(keystring)
currentKeyFile.close()
def get_currentKeyFile(self):
'''
Helps rebuilding currentKey.txt. Kinda redundant, since if it fails the program will fallback to the theKey global variable to do the same.
'''
file_path = os.path.join(data_dir, 'currentKey.txt')
currentKeyFile = open(file_path, 'r')
newKey = currentKeyFile.read()
if not newKey or any(char not in allASCII for char in newKey):
currentKeyFile.close()
raise ValueError('Only printable ASCII chars allowed.')
currentKeyFile.close()
return newKey
def get_defaultKeyFile(self):
'''
Reads defaultKey.txt and returns its contents.
'''
file_path = os.path.join(data_dir, 'defaultKey.txt')
if not os.path.exists(file_path):
newdefKeyFile = open(file_path, 'w')
newdefKeyFile.write(defKey)
newdefKeyFile.close()
defaultKeyFile = open(file_path, 'r')
newKey = defaultKeyFile.read()
if not newKey or any(char not in allASCII for char in newKey):
defaultKeyFile.close()
raise ValueError("'defaultKey.txt' contains non printable ASCII chars.")
defaultKeyFile.close()
return newKey
def init_program(self, reinitKey=None):
'''
Executed when the program is first runs.
Initializes the encryption key and calls all functions necessary to build the code dictionary.
Is also run when the encryption key is changed to rebuild the dictionary and txt files.
'''
global theKey, theCode
if reinitKey:
if any(char not in allASCII for char in reinitKey):
Factory.GenericPop(title='Error',lbl_text='Only printable ASCII characters are accepted.').open()
return
else:
self.set_currentKeyFile(reinitKey)
theKey = self.get_currentKeyFile()
theCode = self.map_Code(theKey)
else: #This should only run the first time the program executes
try:
theKey = self.get_currentKeyFile()
except PermissionError:
print('No storage permissions. Exiting app.')
mainapp.stop()
except:
try:
theKey = self.get_defaultKeyFile()
self.set_currentKeyFile(theKey)
except:
self.set_currentKeyFile(theKey)
theCode = self.map_Code(theKey)
class ScrollableText(ScrollView):
text = StringProperty('')
class ScrollableLabel(ScrollView):
text = StringProperty('')
class EncDecApp(App):
rootMain = ObjectProperty(RootBox())
def build(self):
rootMain = RootBox()
rootMain.init_program()
return rootMain
mainapp = EncDecApp()
if __name__ == "__main__":
_activity = autoclass("org.kivy.android.PythonActivity").mActivity
_external_storage_path = _activity.getExternalFilesDir(None).getPath()
try:
#Environment = autoclass('android.os.Environment')
#path = Environment.getExternalStorageDirectory().getAbsolutePath()
#data_dir = os.path.join(path, 'EncDec')
data_dir = _external_storage_path
if not os.path.exists(data_dir):
os.mkdir(data_dir)
except PermissionError:
print('Failed to create EncDec folder (no permission). Exiting app.')
mainapp.exit()
mainapp.run()