-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymetric.py
271 lines (222 loc) · 8.97 KB
/
symetric.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
from Crypto import Random # use to generate a random byte string of a length we decide
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
from struct import pack
from Crypto.Cipher import Blowfish
from Crypto.Cipher import DES3
from Crypto.Random import get_random_bytes
import main
# Builtins
import base64
import hashlib
from pyDes import *
'''
https://tutorialsoverflow.com/python-encryption-and-decryption/
'''
"""
# Block sizes for AES encryption is 16 bytes or 128 bits. When AES encryption taking place it will divide our data
# into blocks of length 16. This is a fixed size. So what if your data is smaller than the blocksize ? That’s where
# padding comes into play. Now we need to create a padding function. And also we need to create a unpadding function
# so that we can remove the padding during our encryption process.
"""
BS = 16
# pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
# unpad = lambda s: s[0:-s[-1]]
def pad(s):
return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
def unpad(s):
return s[0:-s[-1]]
class AESCipher:
def __init__(self, key):
self.key = hashlib.sha256(key.encode('utf-8')).digest()
def encrypt(self, raw):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw.encode('utf8')))
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]))
'''
cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret Message A')
decrypted = cipher.decrypt(encrypted)
print(encrypted.decode())
print(decrypted.decode())
'''
# https://stackoverflow.com/questions/42568262/how-to-encrypt-text-with-a-password-in-python/44212550#44212550
# Here's how to do it properly in CBC mode, including PKCS#7 padding:
def encryptAES(key, source, encode=True):
key = SHA256.new(key).digest() # use SHA-256 over our key to get a proper-sized AES key
IV = Random.new().read(AES.block_size) # generate IV
encryptor = AES.new(key, AES.MODE_CBC, IV)
padding = AES.block_size - len(source) % AES.block_size # calculate needed padding
source += bytes([padding]) * padding # Python 2.x: source += chr(padding) * padding
data = IV + encryptor.encrypt(source) # store the IV at the beginning and encryptAES
return base64.b64encode(data).decode("latin-1") if encode else data
def decryptAES(key, source, decode=True):
if decode:
source = base64.b64decode(source.encode("latin-1"))
key = SHA256.new(key).digest() # use SHA-256 over our key to get a proper-sized AES key
IV = source[:AES.block_size] # extract the IV from the beginning
decryptor = AES.new(key, AES.MODE_CBC, IV)
data = decryptor.decrypt(source[AES.block_size:]) # decryptAES
padding = data[-1] # pick the padding value from the end; Python 2.x: ord(data[-1])
if data[-padding:] != bytes([padding]) * padding: # Python 2.x: chr(padding) * padding
raise ValueError("Invalid padding...")
return data[:-padding] # remove the padding
# Now if you test it as:
def AESenc():
my_password = input("Please input a secret").encode()
data = input("Please input a string that you want to encrypt").encode()
encrypted = encryptAES(my_password, data)
print("encrypted data: ", encrypted)
menu_symetric()
def AESdec():
my_password = input("Please input a secret").encode()
data = input("Please input a string that you want to decrypt")
try:
decrypted = decryptAES(my_password, data)
print("Congratulations data decrypted succsessfully")
print("decrypted data: ", decrypted.decode())
menu_symetric()
except ValueError:
print("Secret is not correct")
menu_symetric()
'''
my_password = b"secret_AES_key_string_to_encrypt/decrypt_with"
my_data = b"input_string_to_encrypt/decryptAES"
print("key: {}".format(my_password.decode()))
print("data: {}".format(my_data.decode()))
encrypted = encryptAES(my_password, my_data)
print("\nenc: {}".format(encrypted))
decrypted = decryptAES(my_password, encrypted)
print("dec: {}".format(decrypted.decode()))
print("\ndata match: {}".format(my_data == decrypted))
print("\nSecond round....")
encrypted = encryptAES(my_password, my_data)
print("\nenc: {}".format(encrypted))
decrypted = decryptAES(my_password, encrypted)
print("dec: {}".format(decrypted.decode()))
print("\ndata match: {}".format(my_data == decrypted))
'''
def encryptDES(data, key):
# data = "Please encrypt my data"
k = des(key, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
return d
# print ("Decrypted: %r" % k.decrypt(d).decode())
# assert k.decrypt(d, padmode=PAD_PKCS5) == data
def decryptDES(data, key):
# data = "Please encrypt my data"
k = des(key, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
return k.decrypt(data).decode()
def DESenc():
while True:
try:
my_password = input("Please input a secret of exactly 8 characters")
if len(my_password) != 8:
raise ValueError
break
except ValueError:
print("secret must be exactly 8 characters length")
DESenc()
break
data = input("Please input a string that you want to encrypt")
encrypted = encryptDES(data.encode(), my_password.encode())
print("encrypted data: ")
print(base64.b64encode(encrypted).decode("latin-1") if base64.encode else encrypted)
menu_symetric()
def DESdec():
while True:
try:
my_password = input("Please input a secret of exactly 8 characters")
if len(my_password) != 8:
raise ValueError
break
except ValueError:
print("secret must be exactly 8 characters length")
DESdec()
break
data = input("Please input a string that you want to decrypt")
if base64.decode:
data = base64.b64decode(data.encode("latin-1"))
k = des(my_password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
print(data)
# decrypted = decryptDES(data, my_password)
print("Congratulations data decrypted succsessfully")
print("decrypted data: ", k.decrypt(data).decode())
menu_symetric()
def encryptBF(data, key):
pass
def decryptBF(data, key):
pass
def BFenc():
bs = Blowfish.block_size
my_password = input("Please input a secret").encode()
data = input("Please input a string that you want to encrypt")
iv = Random.new().read(bs)
cipher = Blowfish.new(my_password, Blowfish.MODE_CBC, iv)
plen = bs - divmod(len(data), bs)[1]
padding = [plen] * plen
padding = pack('b' * plen, *padding)
msg = iv + cipher.encrypt(data.encode() + padding)
# encrypted = encryptDES(data, my_password)
print("encrypted data: ")
print(base64.b64encode(msg).decode("latin-1") if base64.encode else msg)
menu_symetric()
def BFdec():
bs = Blowfish.block_size
my_password = input("Please input a secret").encode()
data = input("Please input a string that you want to decrypt").encode()
if base64.decode:
msg = base64.b64decode(data)[bs:]
iv = base64.b64decode(data)[:bs]
d = Blowfish.new(my_password, Blowfish.MODE_CBC, iv)
decypted = d.decrypt(msg)
print()
# decrypted = decryptDES(data, my_password)
print("Congratulations data decrypted succsessfully")
print("decrypted data: ", decypted.decode().rstrip("\x03"))
menu_symetric()
def menu_symetric():
print("1: Encrypt AES ")
print("2: Decrypt AES ")
print("3: Encrypt DES ")
print("4: decrypt DES ")
print("5: Encrypt blowfish ")
print("6: Decrypt blowfish ")
print("7: Return ")
while True:
choix_1_1 = int(input("please type your choice : "))
try:
if choix_1_1 in [1, 2, 3, 4, 5, 6, 7]:
if choix_1_1 == 1:
AESenc()
break
if choix_1_1 == 2:
AESdec()
break
if choix_1_1 == 3:
DESenc()
break
if choix_1_1 == 4:
DESdec()
break
elif choix_1_1 == 5:
BFenc()
break
elif choix_1_1 == 6:
BFdec()
break
elif choix_1_1 == 7:
main.menu()
break
else:
print("Please provide integer between 1 and 5")
except ValueError:
print("Please provide integer")
break