-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsecurity.py
445 lines (363 loc) · 12.2 KB
/
security.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
import base64
import string
from exceptions import *
from enums import Algorithms
from pickle import Unpickler, Pickler
class Crypto:
"""
Crypto Class Is Made For Do Encryption And Decryption More Coder Friendly :)
"""
def __init__(self, enc_ls, dec_ls, key):
self.enc_ls = enc_ls
self.dec_ls = dec_ls
self.key = key
def __call__(self, s):
t_enc = s
for i in self.enc_ls:
t_enc = i(t_enc, self.key)
return t_enc
def __eq__(self, o) -> bool:
if len(o.enc_ls) == len(self.enc_ls):
return True
return False
def __gt__(self, o) -> bool:
if len(o.enc_ls) < len(self.enc_ls):
return True
return False
def __ge__(self, o) -> bool:
if len(o.enc_ls) <= len(self.enc_ls):
return True
return False
def __ne__(self, o) -> bool:
if len(o.enc_ls) != len(self.enc_ls):
return True
return False
def __lt__(self, o) -> bool:
if len(o.enc_ls) > len(self.enc_ls):
return True
return False
def __le__(self, o) -> bool:
if len(o.enc_ls) >= len(self.enc_ls):
return True
return False
def enc(self, s):
t_enc = s
for i in self.enc_ls:
t_enc = i(t_enc, self.key)
return t_enc
def dec(self, s):
t_dec = s
for i in self.dec_ls:
t_dec = i(t_dec, self.key)
return t_dec
def __str__(self):
return '('.join([str(i).split(' ')[1] for i in self.enc_ls]) + f"(string)) -> Key Is {self.key}"
class Save:
"""
A Class To Save Some Variables With Some Simple Encryption. Example :
```
Save("file.txt",name="test",family="123",...)()
# Or
handler = Save("file.txt")
handler.add_var("name","Arshia")
handler.add_vars({"nickname":"MrMegaExpert","age":21})
handler.save() # Or handler()
# Or
handler = Save("file.txt")
handler["name"] = "Arshia"
handler.save() # Or handler()
```
"""
def __init__(self, file_name, **kwargs):
self.file_name = file_name
self.vars_list = kwargs
def add_var(self, key, value):
self.vars_list[key] = value
def add_vars(self, **kwargs):
self.vars_list.update(kwargs)
def __setitem__(self, key, value):
self.vars_list[key] = value
def __getitem__(self, key):
return self.vars_list[key]
def __call__(self):
Pickler(open(self.file_name, "wb")).dump(self.vars_list)
def save(self):
Pickler(open(self.file_name, "wb")).dump(self.vars_list)
class Load:
"""
A Class To Load Saved Variables. Example :
```
def test():
print(name)
Load("file.txt")(test)
# Or
handler = Load("file.txt")
print(handler.vars) # All Variables As Dictionary
# Or
Load("file.txt")()
print(name) # If You Saved name It Will Be Shown :)
```
"""
def __init__(self, file_name):
self.file_name = file_name
self.vars_list = Unpickler(open(self.file_name, "rb")).load()
def vars(self):
return self.vars_list
def __call__(self, module=None):
for i, j in self.vars_list.items():
if not module:
globals()[i] = j
else:
setattr(module, i, j)
def load(self, module=None):
for i, j in self.vars_list.items():
if not module:
globals()[i] = j
else:
setattr(module, i, j)
def _xor(string, key=0):
"""
xor function. got string And key At The End; It Will Encrypt/Decrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
if type(key) == int:
ans = ""
for i in string:
ans += chr(i ^ key)
else:
raise TypeError("key Type Must Be Int.")
return ans
def _b64_en(string, k=""):
"""
base64 Encoder function. got string And key (Fake) At The End; It Will Encrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b64encode(string).decode('utf-8')
def _b64_de(string, k=""):
"""
base64 Decoder function. got string And key (Fake) At The End; It Will Decrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b64decode(string).decode('utf-8')
def _b32_en(string, k=""):
"""
base32 Encoder function. got string And key (Fake) At The End; It Will Encrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b32encode(string).decode('utf-8')
def _b32_de(string, k=""):
"""
base32 Decoder function. got string And key (Fake) At The End; It Will Decrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b32decode(string).decode('utf-8')
def _b16_en(string, k=""):
"""
base16 Encoder function. got string And key (Fake) At The End; It Will Encrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b16encode(string).decode('utf-8')
def _b16_de(string, k=""):
"""
base16 Decoder function. got string And key (Fake) At The End; It Will Decrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b16decode(string).decode('utf-8')
def _b85_en(string, k=""):
"""
base85 Encoder function. got string And key (Fake) At The End; It Will Encrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b85encode(string).decode('utf-8')
def _b85_de(string, k=""):
"""
base85 Decoder function. got string And key (Fake) At The End; It Will Decrypt Your Data.
"""
if type(string) == str:
string = bytes(string, encoding='utf-8')
elif type(string) == bytes:
pass
else:
raise TypeError("Type Should Be 'str' Or 'bytes'.")
return base64.b85decode(string).decode('utf-8')
def _cipher_en(s, key=1):
"""
Cipher Encoder function. got string And key At The End; It Will Encrypt Your,Data.
"""
if type(key) == str:
try:
key = int(key)
except:
raise TypeError("Type Should Be 'int'.")
elif type(key) == int:
pass
else:
raise TypeError("Type Should Be 'int'.")
slow = string.ascii_lowercase + string.ascii_lowercase
sup = string.ascii_uppercase + string.ascii_uppercase
ans = ""
for i in s:
if i in string.ascii_lowercase:
ans += slow[slow.index(i) + key]
elif i in string.ascii_uppercase:
ans += sup[sup.index(i) + key]
else:
ans += i
return ans
def _cipher_de(s, key=1):
"""
Cipher Decoder function. got string And key At The End; It Will Decrypt Your Data.
"""
if type(key) == str:
try:
key = int(key)
except:
raise TypeError("Type Should Be 'int'.")
elif type(key) == int:
pass
else:
raise TypeError("Type Should Be 'int'.")
slow = string.ascii_lowercase + string.ascii_lowercase
sup = string.ascii_uppercase + string.ascii_uppercase
ans = ""
for i in s:
if i in string.ascii_lowercase:
ans += slow[slow.index(i) - key]
elif i in string.ascii_uppercase:
ans += sup[sup.index(i) - key]
else:
ans += i
return ans
def _rot13(string):
"""
ROT13 function. It Will Encrypt Your Data In This Algorythm.
"""
slow = string.ascii_lowercase
sup = string.ascii_uppercase
ans = ""
for i in string:
if i in string.ascii_lowercase:
ans += slow[(slow.index(i) + 13) % 26]
elif i in string.ascii_uppercase:
ans += sup[(sup.index(i) + 13) % 26]
else:
ans += i
return ans
def _unrot13(string):
"""
ROT13 Decoder function. It Will Decrypt Your Data In This Algorythm.
"""
slow = string.ascii_lowercase
sup = string.ascii_uppercase
ans = ""
for i in string:
if i in string.ascii_lowercase:
ans += slow[(slow.index(i) - 13) % 26]
elif i in string.ascii_uppercase:
ans += sup[(sup.index(i) - 13) % 26]
else:
ans += i
return ans
def make_enc(alg, key=b""):
"""
make_enc Function Will Make You An instance Of Crypto Class That Contains A
Chain Of Encryption Algorithm. In Fact You Are Free To Use Just One Or More.
Args/Kwargs :
* alg -> The Algorithm That Can Be Like Algorithms.XOR Or Like
[Algorithms.XOR,Algorithms.Base64]
* key -> The Target Key That You Want To Use In Encryption Process.
Example :
```a = make_enc([Algorithms.XOR,Algorithms.Base64],10)
a.enc("Hello") # Encrypt "Hello" Equals "Qm9mZmU="
a.dec("Qm9mZmU=") # Decrypt "Qm9mZmU" Equals "Hello"```
"""
if str(type(alg)) == "<enum 'Algorithms'>":
if alg.name == Algorithms.XOR.name:
return Crypto([_xor], [_xor], key)
elif alg.name == Algorithms.ROT13.name:
return Crypto([_rot13], [_unrot13], key)
elif alg.name == Algorithms.Base64.name:
return Crypto([_b64_en], [_b64_de], key)
elif alg.name == Algorithms.Cipher.name:
return Crypto([_cipher_en], [_cipher_de], key)
elif alg.name == Algorithms.Base16.name:
return Crypto([_b16_en], [_b16_de], key)
elif alg.name == Algorithms.Base32.name:
return Crypto([_b32_en], [_b32_de], key)
elif alg.name == Algorithms.Base85.name:
return Crypto([_b85_en], [_b85_de], key)
else:
raise AlgorithmError(
f"This Algorithm Is Not Available. We Will Be Happy If You Help Us To Make It :)\nGithub : https://github.com/Arshiatmi/Pysha")
elif type(alg) == list or type(alg) == set or type(alg) == tuple:
ls_en = []
ls_de = []
for i in alg:
if hasattr(i, 'name') and i.name == Algorithms.XOR.name:
ls_en.append(_xor)
ls_de.append(_xor)
elif hasattr(i, 'name') and i.name == Algorithms.Base64.name:
ls_en.append(_b64_en)
ls_de.append(_b64_de)
elif hasattr(i, 'name') and i.name == Algorithms.Cipher.name:
ls_en.append(_cipher_en)
ls_de.append(_cipher_de)
elif hasattr(i, 'name') and i.name == Algorithms.Base16.name:
ls_en.append(_b16_en)
ls_de.append(_b16_de)
elif hasattr(i, 'name') and i.name == Algorithms.Base32.name:
ls_en.append(_b32_en)
ls_de.append(_b32_de)
elif hasattr(i, 'name') and i.name == Algorithms.Base85.name:
ls_en.append(_b85_en)
ls_de.append(_b85_de)
elif hasattr(i, 'name') and i.name == Algorithms.ROT13.name:
ls_en.append(_rot13)
ls_de.append(_unrot13)
else:
raise AlgorithmError(
f"Type {i} Is Not Supported. Just (Algorithms.Base64/Algorithms.XOR/Algorithms.Cypher) Is Supported.")
return Crypto(ls_en, ls_de[::-1], key)
else:
raise AlgorithmError(
f"This Type Of Algorithm Is Not Supported. Just enum.EnumMeta (Algorithms.Base64/...),list and set Are Supported.")