· 6 years ago · Aug 21, 2019, 04:06 PM
1import os, random, struct
2from Cryptodome.Cipher import AES
3
4
5def decrypt_file(key, input_file):
6 """ Decrypts a file using AES CBC mode with the
7 given key.
8 """
9
10 # This the block size of data we read, decrypt and write.
11 # It should be a multiple of 16 for AES.
12 chunksize=16*4*1024
13
14 # get rid of the .aes ending
15 output_filename = os.path.splitext(input_file)[0]
16
17 with open(input_file, 'rb') as in_file:
18 # retrieve the original size of the encrypted data
19 origsize = struct.unpack('<Q', in_file.read(struct.calcsize('Q')))[0]
20 # retrieve the initialization vector
21 initial_vector = in_file.read(16)
22 decryptor = AES.new(key, AES.MODE_CBC, initial_vector)
23
24 # read block for block the encrypted data, decrypt and write
25 with open(output_filename, 'wb') as out_file:
26 while True:
27 chunk = in_file.read(chunksize)
28 if len(chunk) == 0:
29 break
30 out_file.write(decryptor.decrypt(chunk))
31
32 out_file.truncate(origsize)
33
34
35def main():
36 # secret_key = b'--> I am a random secret key <--'
37
38 secret_key = input("Give me your secret key (16, 24 or 32 characters):").encode("utf-8")
39 while len(secret_key) != 16 and len(secret_key) != 24 and len(secret_key) != 32:
40 print("\nThere was an error! Please try again with 16, 24 or 32 characters:")
41 secret_key = input("\nGive me your secret key (16, 24 or 32 characters):").encode("utf-8")
42
43 path = input("\nGive me a path or file to decrypt:")
44 while os.path.isdir(path) != True and os.path.isfile(path) != True:
45 print("\nThere was an error! Please try again with a correct path or file to decrypt:")
46 path = input("\nGive me a path or file to decrypt:")
47
48 # path = directory?
49 if os.path.isdir(path):
50 files = []
51 # traverse all subfolders and save path + filename
52 for root, d_names, f_names in os.walk(path):
53 for f in f_names:
54 files.append(os.path.join(root, f)) # these are all files in all subfolders
55 for file in files:
56 # better skip not encrypted files
57 if file.endswith(".aes"):
58 print("\nDecrypting ", file)
59 decrypt_file(secret_key, file)
60 # after decryption we could delete the file.. ;)
61 # just remove the '#' in the next line
62 # os.remove(file)
63
64 # path is no directory, but must be a file
65 else:
66 # better skip not encrypted files
67 if path.endswith(".aes"):
68 print("\nDecrypting ", path)
69 decrypt_file(secret_key, path)
70 # after decryption we could delete the file.. ;)
71 # just remove the '#' in the next line
72 # os.remove(path)
73
74main()