import json import funcy from Crypto.Cipher import AES from Crypto import Random def decrypt(key_file, filename): with open(key_file, 'rb') as passFile: key = passFile.read() chunksize = 64 * 1024 with open(filename, 'rb') as infile: file_size = int(infile.read(16)) IV = infile.read(16) decryptor = AES.new(key, AES.MODE_CBC, IV) result_bytes = b'' while True: chunk = infile.read(chunksize) if len(chunk) == 0: break result_bytes += decryptor.decrypt(chunk) result_bytes = result_bytes[:file_size] return result_bytes def encrypt(parameters, key_file, filename): with open(key_file, 'rb') as passFile: key = passFile.read() chunksize = 64 * 1024 object_to_encrypt = json.dumps(parameters) object_to_encrypt = object_to_encrypt.encode('UTF-8') output_file = filename filesize = str(len(object_to_encrypt)).zfill(16) IV = Random.new().read(16) encryptor = AES.new(key, AES.MODE_CBC, IV) with open(output_file, 'wb') as outfile: outfile.write(filesize.encode('UTF-8')) outfile.write(IV) for chunk in funcy.chunks(chunksize, object_to_encrypt): if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += b' ' * (16 - (len(chunk) % 16)) outfile.write(encryptor.encrypt(chunk))