· 6 years ago · Aug 23, 2019, 06:34 AM
1# Author: howdoyouturnthison
2# How to encrypt and decrypt your data with AES and python:
3# https://www.youtube.com/watch?v=YqY6H1IPBDY
4
5import os, random, struct
6from Cryptodome.Cipher import AES
7
8
9def encrypt_file(key, input_file):
10 """ Encrypt a file using AES CBC mode.
11
12 key:
13 The encryption key - This is our secret to
14 encrypt and decrypt.
15 Should be 16 (AES-128), 24 (AES-192 ) or
16 32 bytes (AES-256) (characters) long.
17
18 input_file:
19 The input file
20 """
21
22 # This the block size of data we read, encrypt and write.
23 # It should be a multiple of 16 for AES.
24 chunksize=16*4*1024
25
26 output_filename = input_file + '.aes'
27
28 # 16 random bytes as initialization vector
29 initial_vector = os.urandom(16) # urandom: best method :)
30
31 encryptor = AES.new(key, AES.MODE_CBC, initial_vector)
32 filesize = os.path.getsize(input_file)
33
34 try:
35 with open(input_file, 'rb') as in_file:
36 try:
37 with open(output_filename, 'wb') as out_file:
38 # put the initial_vector at the beginning of the file
39 # we need to read from this position to decrypt correctly later
40 out_file.write(struct.pack('<Q', filesize))
41 out_file.write(initial_vector)
42
43 # go block for block through the data
44 while True:
45 # read a block of data
46 chunk = in_file.read(chunksize)
47 # if chunk == 0, we are at the end
48 if len(chunk) == 0:
49 break
50 # else we need to fill the last block of bytes up to 16
51 elif len(chunk) % 16 != 0:
52 chunk += b' ' * (16 - len(chunk) % 16)
53 # encrypt this block and append it to the file
54 out_file.write(encryptor.encrypt(chunk))
55 except PermissionError:
56 print("\nCouldn't write ", output_filename)
57 except PermissionError:
58 print("\nCouldn't read ", input_file)
59
60
61def main():
62 #secret_key = b'--> I am a random secret key <--'
63
64 secret_key = input("Give me a secret key (16, 24 or 32 characters):").encode("utf-8")
65 while len(secret_key) != 16 and len(secret_key) != 24 and len(secret_key) != 32:
66 print("\nThere was an error! Please try again with 16, 24 or 32 characters:")
67 secret_key = input("\nGive me a secret key (16, 24 or 32 characters):").encode("utf-8")
68
69 path = input("\nGive me a path or file to encrypt:")
70 while os.path.isdir(path) != True and os.path.isfile(path) != True:
71 print("\nThere was an error! Please try again with a correct path or file to encrypt:")
72 path = input("\nGive me a path or file to encrypt:")
73
74 # path = directory?
75 if os.path.isdir(path):
76 files = []
77 # traverse all subfolders and save path + filename
78 for root, d_names, f_names in os.walk(path):
79 for f in f_names:
80 files.append(os.path.join(root, f)) # these are all files in all subfolders
81 for file in files:
82 # better skip already encrypted files
83 if not file.endswith(".aes"):
84 print("\nEncrypting ", file)
85 encrypt_file(secret_key, file)
86 # after encryption we could delete the file.. ;)
87 # just remove the '#' in the next line
88 #os.remove(file)
89
90 # path is no directory, but must be a file
91 else:
92 # better skip already encrypted files
93 if not path.endswith(".aes"):
94 print("\nEncrypting ", path)
95 encrypt_file(secret_key, path)
96 # after encryption we could delete the file.. ;)
97 # just remove the '#' in the next line
98 #os.remove(path)
99
100if __name__ == '__main__':
101 main()