· 7 years ago · May 24, 2018, 08:36 PM
1import abc
2import binascii
3import json
4
5
6class CryptoAlg(metaclass=abc.ABCMeta):
7
8 def __init__(self, method):
9 self.method = method
10
11 def encrypt_file(self, input_file, output_file, key=None):
12 data = {}
13 array = []
14 with open(input_file, 'r') as in_file:
15 with open(output_file, 'w') as out_file:
16 file = in_file.read()
17 if len(file) % 16 != 0:
18 file += ' ' * (16 - len(file) % 16)
19 array.append(self._encrypt(file, key))
20 data[self.method] = {'Description': 'crypted file', 'Method': self.method, 'File name': input_file,
21 'data': " ".join(x.decode() for x in array)}
22 json.dump(data, out_file, indent=2)
23
24 def decrypt_file(self, input_file, output_file, key=None):
25 data_print = {}
26 with open(output_file, 'w') as out_file:
27 data = self.get_data(input_file, self.method)
28 data_print[self.method] = {'Description': 'decrypted file', 'Method': self.method, 'File name': input_file,
29 'data': self._decrypt(data.encode(), key).decode()}
30 json.dump(data_print, out_file, indent=2)
31
32 def store_key_and_iv(self, file, type, key, iv):
33 data = {type: {'secretKey': binascii.hexlify(key).decode('ascii'), 'iv': binascii.hexlify(iv).decode('ascii')}}
34 with open(file, 'w') as file:
35 json.dump(data, file, indent=2)
36
37 @staticmethod
38 def get_data(input, method):
39 with open(input, 'r') as file:
40 d = json.load(file)
41 data = d[method]['data']
42 return data
43
44 @abc.abstractmethod
45 def _encrypt(self, chunk, key=None):
46 pass
47
48 @abc.abstractmethod
49 def _decrypt(self, chunk, key=None):
50 pass