-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.py
More file actions
280 lines (201 loc) · 8.97 KB
/
Copy pathproject.py
File metadata and controls
280 lines (201 loc) · 8.97 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
import hashlib
import math
import os
import re
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import tkinter as tk
from tkinter import filedialog
def get_aes_key_from_string(s: str, key_size=16) -> bytes:
assert key_size in (16, 24, 32), "Invalid key size"
hash_bytes = hashlib.sha256(s.encode()).digest()
return hash_bytes[:key_size]
def encrypt(plainbytes: bytes, key: bytes) -> bytes:
cipher = AES.new(key, AES.MODE_ECB)
padded = pad(plainbytes, AES.block_size)
return cipher.encrypt(padded)
def decrypt(ciphertext: bytes, key: bytes) -> bytes:
cipher = AES.new(key, AES.MODE_ECB)
decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
return decrypted
def encode_file(full_path: str, entered_key: str):
with open(full_path, "rb") as input_file:
file_bytes = input_file.read()
encoded_bytes = encrypt(file_bytes, get_aes_key_from_string(entered_key))
encoded_file_path = full_path+".encoded"
with open(encoded_file_path, "wb") as encoded_file:
encoded_file.write("<<<EncodedWithTrampoline>>>".encode() + encoded_bytes + "<<<EncodedWithTrampoline>>>".encode())
return encoded_file_path
def decode_file(full_path: str, entered_key: str):
with open(full_path, "rb") as encoded_file:
encoded_bytes = encoded_file.read()
encoded_bytes = encoded_bytes.removeprefix(b"<<<EncodedWithTrampoline>>>")
encoded_bytes = encoded_bytes.removesuffix(b"<<<EncodedWithTrampoline>>>")
decoded_bytes = decrypt(encoded_bytes, get_aes_key_from_string(entered_key))
directory = os.path.dirname(full_path)
file_name = os.path.basename(full_path)
file_name = "decoded_" + file_name.removesuffix(".encoded")
new_path = os.path.join(directory, file_name)
with open(new_path, "wb") as decoded_file:
decoded_file.write(decoded_bytes)
return new_path
def get_list_of_encoded_files(directory_path):
list_of_files = []
for entry in os.listdir(directory_path):
full_path = os.path.join(directory_path, entry)
if os.path.isfile(full_path):
if check_validity(full_path):
list_of_files.append(full_path)
return list_of_files
def check_validity(full_path):
with open(full_path, "rb") as encoded_file:
encoded_bytes = encoded_file.read()
if encoded_bytes.startswith(b"<<<EncodedWithTrampoline>>>") and encoded_bytes.endswith(b"<<<EncodedWithTrampoline>>>"):
return True
return False
def file_splitter(full_path, parts_count):
with open(full_path, "rb") as f:
file_content = f.read()
original_file_dir = os.path.dirname(full_path)
original_file_name = os.path.basename(full_path)
file_extension = original_file_name.split(".")[-1]
file_hash = hashlib.sha256(file_content).hexdigest()
part_size = math.ceil(len(file_content) / parts_count)
file_paths = []
for i in range(parts_count):
fname = original_file_name + f".part{i+1}"
with open(fname, "wb") as f:
f.write(f"[part{i+1}-{file_extension}-{file_hash}]".encode())
f.write(file_content[i*part_size:(i+1)*part_size])
file_paths.append(os.path.join(original_file_dir, fname))
return file_paths
def file_joiner(file_paths):
try:
invalid = False
fcontents = []
for fpath in file_paths:
with open(fpath, "rb") as f:
fcontent = f.read()
if not fcontent.startswith(b"[part"):
invalid = True
break
fcontents.append(fcontent)
if not invalid:
fcontents = sorted(fcontents, key=lambda x:x[:6])
raw_contents = []
desc_hash = None
file_extension = None
for fcontent in fcontents:
pattern = re.compile(rb"^\[part.*?\]")
match = pattern.match(fcontent)
if match:
desc = match.group(0)
desc = desc.decode()
if not file_extension:
file_extension = desc.split("-")[1]
elif file_extension != desc.split("-")[1]:
invalid = True
break
if not desc_hash:
desc_hash = desc.split("-")[-1][:-1]
elif desc_hash != desc.split("-")[-1][:-1]:
invalid = True
break
raw_content = fcontent[match.end():]
raw_contents.append(raw_content)
else:
invalid = True
break
if invalid:
print("One or more files from the files you provided is not a split file generated by me or the files aren't generated from the same file!")
else:
final_content = b"".join(raw_contents)
if hashlib.sha256(final_content).hexdigest() == desc_hash:
file_dir = os.path.dirname(file_paths[0])
new_path = os.path.join(file_dir, f"file-{desc_hash}.{file_extension}")
with open(new_path, "wb") as f:
f.write(final_content)
return new_path, final_content
else:
print("Unfortunately the stored hash does not match the result file's hash")
except FileNotFoundError as ex:
print("One or more of the paths you passed wasn't a valid file path")
except Exception as ex:
print("One of the files wasn't how is supposed to be")
def main():
root = tk.Tk()
root.withdraw()
print("Welcome to Trampoline file encoder :)")
while True:
inp = input("What do you want to do?" \
"\n\t1: Encode a file" \
"\n\t2: List of encoded files in a directory" \
"\n\t3: Decode a file" \
"\n\t4: Split a file" \
"\n\t5: Rejoin files" \
"\n\t0: Exit" \
"\n: "
)
if inp == "1":
full_path = input("Enter the file full path: ")
entered_key = input("Enter a key to encrypt the file with: ")
try:
encryption_path = encode_file(full_path, entered_key)
print("Encryption Done")
print("Encrypted file:", encryption_path)
except FileNotFoundError as ex:
print("\nError: The path you entered wasn't a valid path to a file!")
elif inp == "2":
directory_path = input("Enter the full path of the directory: ")
try:
list_of_files = get_list_of_encoded_files(directory_path)
print()
for f in list_of_files:
print(f, "is encoded")
if not list_of_files:
print("No encoded files are found in this directory")
except FileNotFoundError as ex:
print("\nErro: Not a valid path")
elif inp == "3":
full_path = input("Enter the full path of the encoded file: ")
entered_key = input("Enter the key you used to encode: ")
try:
if check_validity(full_path):
decryption_path = decode_file(full_path, entered_key)
print("Decryption Done")
print("Decrypted file:", decryption_path)
else:
print("Not a valid encoded file!")
except FileNotFoundError as ex:
print("\nError: Not a valid path to a file")
elif inp == "4":
try:
full_path = input("Enter the full path of the file: ")
parts_count = input("Enter the number of parts you want it to be split to (max 8): ")
parts_count = min(8, int(parts_count))
file_paths = file_splitter(full_path, parts_count)
print("Parts' path:")
print("\n".join(file_paths))
except ValueError as ex:
print("The part count you entered wasn't a number")
except FileNotFoundError as ex:
print("\nError: Not a valid path to a file")
elif inp == "5":
root.update()
root.attributes('-topmost', True) # force dialogs on top
root.lift()
file_paths = filedialog.askopenfilenames(
title="Select files",
filetypes=[("All Files", "*.*"), ("Text Files", "*.txt")]
)
if file_paths:
new_path, _ = file_joiner(file_paths)
print("Your original file was rejoined to this path: ", new_path)
elif inp == "0":
print("Exiting the program.")
exit()
else:
print("Invalid input")
print("\n")
if __name__ == "__main__":
main()