-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplecrypt-cli.py
363 lines (261 loc) · 14.1 KB
/
simplecrypt-cli.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
import sys
from colorama import Fore, Style, init, Back
init(autoreset=True)
def checklib(lib):
import importlib
import subprocess
try:
importlib.import_module(lib)
return True
except ImportError:
#return False
try:
subprocess.check_call(["pip", "install", lib])
print("The lib" +lib+ " was installed successfully.")
return True
except subprocess.CalledProcessError:
print("Wasn't possible to install the lib " +lib+". Check your environment and try again mannualy.")
return False
def print_help():
txt = fr"""
.--------.
/ .------. \
/ / \ \
| | | |
_| |________| |_
.' |_| |_| '.
'._____ ____ _____.'
| .'____'. |
'.__.'.' '.'.__.'
'.__ SIMPLECRYPT |
| '.'. 2.0.'.' |
'.____'.____.'____.'
'.________________.'
https://github.com/pedropamn/simplecrypt
Usage:
For files:
{Fore.GREEN}python simplecrypt-cli.py [--encrypt | --decrypt] /path/to/file.ext{Style.RESET_ALL}
For folders:
{Fore.GREEN}python simplecrypt-cli.py [--encrypt | --decrypt] /path/to/folder/{Style.RESET_ALL}
"""
print(txt)
#Crypt Function
def crypt(password, fullfilepath, keepOriginal):
import pyAesCrypt
#get file extension
#filename = fullfilepath.splitext(f)[0]
#extension = fullfilepath.splitext(f)[1]
# encryption/decryption buffer size - 64K
bufferSize = 64 * 1024
# encrypt
try:
done = True
#Must be firstly generated as .aes. Other extensions fail on decrypt
pyAesCrypt.encryptFile(fullfilepath, fullfilepath + ".aes", password, bufferSize)
import os
if keepOriginal == False:
#Delete original file
os.remove(fullfilepath)
#Rename .aes file to original extension
os.rename(fullfilepath + ".aes", fullfilepath)
else:
#Get original extension
original_ext = get_file_extension(fullfilepath) #returns '.txt, .doc, etc...'
#print(original_ext)
#File path without extension
file_path_without_ext = os.path.splitext(fullfilepath)[0]
#print(file_path_without_ext)
#Put timestamp on file name to make it unique. If user keeps the original file and already have a 'file_encrypted.extension' on folder, it will overwrite it.
timestamp = str(getTimestamp())
#Rename encrypted file
os.rename(fullfilepath + ".aes", file_path_without_ext + "_encrypted_" + timestamp + original_ext)
except Exception as e:
done = False
return done
#Decrypt Function
def decrypt(password, fullfilepathtodecrypt, keepOriginal):
import pyAesCrypt
import os
# encryption/decryption buffer size - 64K
bufferSize = 64 * 1024
# encrypt
try:
done = True
#import os.path
#new_file_path_and_name = os.path.splitext(fullfilepathtodecrypt)[0] #everything before .aes
pyAesCrypt.decryptFile(fullfilepathtodecrypt, fullfilepathtodecrypt + '.temp', password, bufferSize)
if keepOriginal == False:
#Delete original file
os.remove(fullfilepathtodecrypt)
#Rename .temp file to original extension
os.rename(fullfilepathtodecrypt + ".temp", fullfilepathtodecrypt)
else:
#Get original extension
original_ext = get_file_extension(fullfilepathtodecrypt) #returns '.txt, .doc, etc...'
#File path without extension
file_path_without_ext = os.path.splitext(fullfilepathtodecrypt)[0]
#Replace the 'encrypted' word for "decrypted", if any (by default, the 'encrypted' word is attached to the file if encrypted with SimpleCrypt)
file_path_without_ext_replace = file_path_without_ext.replace('_encrypted','_decrypted')
#If replaced...
if file_path_without_ext_replace != file_path_without_ext:
#"Decrypted" word was on filename. Just add timestamp on it
timestamp = str(getTimestamp())
else:
#"Decrypted" word was not on file name. Add it (and timestamp too)
timestamp = str(getTimestamp()) + '_decrypted'
#Rename decrypted file
os.rename(fullfilepathtodecrypt + '.temp', file_path_without_ext_replace + "_" + timestamp + original_ext)
except Exception as e:
done = False
return done
def get_file_extension(file_path):
import os
if '.' in os.path.basename(file_path):
file_extension = os.path.splitext(file_path)[1]
else:
file_extension = ""
return file_extension
def getTimestamp():
import time
timestamp = int(time.time())
return timestamp
##### START #####
#Check libs
check = False
modules = ["colorama","pyAesCrypt", "getpass"]
for module in modules:
check = checklib(module)
if check == True:
arg = ""
#Is there any args in command line?
try:
if sys.argv[1] == "--encrypt":
fullpath = sys.argv[2]
import getpass
password = getpass.getpass("Type the password: ")
while True:
answer = input("\n\nKeep Original file(s)? \nIf no, it will overwrite the file (be careful) (Y/N): ").strip().upper()
if answer in ("Y", "N"):
if answer == "Y":
keep_original = True
else:
keep_original = False
break
else:
print(f"{Fore.YELLOW}Invalid answer. Please, type 'Y' or'N' ")
import os
if os.path.isfile(fullpath):
freturn = crypt(password, fullpath, keep_original)
if freturn == True:
print(Fore.GREEN+Back.YELLOW+Style.BRIGHT+"File encrypted successfully!")
else:
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"Something went wrong. Check the path, password and file permissions")
#It's a folder
else:
error_list = []
done_list = []
#If 'isfile' fails, throw the 'else' (go here). So, if it's not a file, firstly check if the path to the supposed folder exists
if not os.path.exists(fullpath):
#It's not a file or folder
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"This file or folder doesn't exists")
else:
#Loop all folder content (will list subfolder, but will not enter on it. os.walk enter in subfolders) and run the crypt function on each file
folder_content = os.listdir(fullpath)
#Check if folder is empty
if folder_content == []:
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"Folder is empty")
else:
#Loop
for item in folder_content:
#Get whole item path (path/to/item)
file_path = os.path.join(fullpath, item)
#Ignore subfolders
if os.path.isfile(file_path):
freturn = crypt(password, file_path, keep_original)
if freturn == False:
error_list.append(item)
else:
done_list.append(item)
if len(error_list) == 0:
print(Fore.GREEN+Back.YELLOW+Style.BRIGHT+"All files were encrypted successfully!")
#Check for dir separator (/ or \) on the end of 'fullpath'. "Select folder" option not include it and, even if it included, it could be removed by the user. Separator is necessary on the end of path for "Open folder" button to open the correct folder, not the parent one
if not fullpath.endswith(os.sep):
# Concats a empty string. It will add dir separator at the end (/ or \)
fullpath = os.path.join(fullpath, "")
else:
all_errors = '\n'
all_dones = '\n'
for error in error_list:
all_errors = all_errors + str(error) + '\n'
for done in done_list:
all_dones = all_dones + str(done) + '\n'
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"We got problems on following files:\n "+all_errors+"\n Check their permissions and password\n\n✅ In addition, the following files were encrypted successfully\n"+all_dones)
elif sys.argv[1] == "--decrypt":
fullpath = sys.argv[2]
import getpass
password = getpass.getpass("Type the password: ")
while True:
answer = input("\n\nKeep Original file(s)? \nIf no, it will overwrite the file (be careful) (Y/N): ").strip().upper()
if answer in ("Y", "N"):
if answer == "Y":
keep_original = True
else:
keep_original = False
break
else:
print(f"{Fore.YELLOW}Invalid answer. Please, type 'Y' or'N' ")
import os
if os.path.isfile(fullpath):
freturn = decrypt(password, fullpath, keep_original)
if freturn == True:
print(Fore.GREEN+Back.YELLOW+Style.BRIGHT+"File decrypted successfully!")
else:
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"Something went wrong. Check the path, password and file permissions")
#It's a folder
else:
error_list = []
done_list = []
#If 'isfile' fails, throw the 'else' (go here). So, if it's not a file, firstly check if the path to the supposed folder exists
if not os.path.exists(fullpath):
#It's not a file or folder
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"This file or folder doesn't exists")
else:
#Loop all folder content (will list subfolder, but will not enter on it. os.walk enter in subfolders) and run the crypt function on each file
folder_content = os.listdir(fullpath)
#Check if folder is empty
if folder_content == []:
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"Folder is empty")
else:
#Loop
for item in folder_content:
#Get whole item path (path/to/item)
file_path = os.path.join(fullpath, item)
#Ignore subfolders
if os.path.isfile(file_path):
freturn = decrypt(password, file_path, keep_original)
if freturn == False:
error_list.append(item)
else:
done_list.append(item)
if len(error_list) == 0:
print(Fore.GREEN+Back.YELLOW+Style.BRIGHT+"All files were decrypted successfully!")
#Check for dir separator (/ or \) on the end of 'fullpath'. "Select folder" option not include it and, even if it included, it could be removed by the user. Separator is necessary on the end of path for "Open folder" button to open the correct folder, not the parent one
if not fullpath.endswith(os.sep):
# Concats a empty string. It will add dir separator at the end (/ or \)
fullpath = os.path.join(fullpath, "")
else:
all_errors = '\n'
all_dones = '\n'
for error in error_list:
all_errors = all_errors + str(error) + '\n'
for done in done_list:
all_dones = all_dones + str(done) + '\n'
print(Fore.RED+Back.YELLOW+Style.BRIGHT+"We got problems on following files:\n "+all_errors+"\n Check their permissions and password\n\n✅ In addition, the following files were decrypted successfully\n"+all_dones)
#Not acceptable or malformed args
else:
print_help()
#No args
except IndexError as e:
print_help()
else:
print("Some libs could'n be imported. Install it mannualy via pip")