-
Notifications
You must be signed in to change notification settings - Fork 0
/
task_1_easy.sage
217 lines (177 loc) · 10 KB
/
task_1_easy.sage
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
import sys
import os
import argparse
import constants
from importlib import import_module
from csv import writer
from claasp.cipher_modules.models.utils import set_fixed_variables
from claasp.utils.sage_scripts import get_ciphers, get_cipher_type
from claasp.name_mappings import INPUT_KEY, INPUT_PLAINTEXT
sys.path.insert(0, "/home/sage/tii-claasp")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
files_list = get_ciphers()
parser = argparse.ArgumentParser(description='task 1')
parser.add_argument('-m', action="store", dest="model", default='sat')
args = parser.parse_args()
def remove_repetitions(param):
for i in range(len(param)):
if 'number_of_rounds' in param[i]:
param[i].pop("number_of_rounds")
return [dict(t) for t in {tuple(d.items()) for d in param}]
def handle_solution(solution):
if isinstance(solution, list):
build_time = solution[0]['building_time_seconds']
memory = solution[0]['memory_megabytes']
weight = solution[0]['total_weight']
if args.model == 'cp':
solve_time = solution[0]['solving_time_seconds']
else:
solve_time = sum([sol['solving_time_seconds'] for sol in solution])
return build_time, solve_time, memory, len(solution), weight
return solution['building_time_seconds'], solution['solving_time_seconds'], solution['memory_megabytes'], solution['total_weight']
def generate_parameters(creator_file):
creator_type = get_cipher_type(creator_file)
creator_module = import_module(f'.ciphers.{creator_type}.{creator_file[:-3]}', 'claasp')
available_parameters = []
for name in creator_module.__dict__:
if 'BlockCipher' in name or 'HashFunction' in name or 'Permutation' in name:
creator = creator_module.__dict__[name]
available_parameters = creator_module.__dict__['PARAMETERS_CONFIGURATION_LIST']
break
available_parameters = remove_repetitions(available_parameters)
return creator, available_parameters
def generate_fixed_variables(cipher):
fixed_variables = []
if INPUT_PLAINTEXT in cipher.inputs:
plaintext_size = cipher.inputs_bit_size[cipher.inputs.index(INPUT_PLAINTEXT)]
fixed_variables.append(
set_fixed_variables(
INPUT_PLAINTEXT,
'not_equal',
list(range(plaintext_size)),
[0] * plaintext_size))
if INPUT_KEY in cipher.inputs:
key_size = cipher.inputs_bit_size[cipher.inputs.index(INPUT_KEY)]
if cipher.type != 'hash_function':
fixed_variables.append(set_fixed_variables(INPUT_KEY, 'equal', list(range(key_size)), [0] * key_size))
else:
fixed_variables.append(set_fixed_variables(INPUT_KEY, 'not_equal', list(range(key_size)), [0] * key_size))
return fixed_variables
def timeout(func, args=(), kwargs={}, timeout_duration=600):
@fork(timeout=timeout_duration, verbose=False)
def my_new_func():
return func(*args, **kwargs)
return my_new_func()
if __name__ == "__main__":
if not os.path.exists(f'scripts/task_1_easy_results/{args.model}'):
os.makedirs(f'scripts/task_1_easy_results/{args.model}')
failure_queue = dict.fromkeys(constants.MODEL_LIST[args.model]['solver_list'])
for solver in failure_queue:
failure_queue[solver] = []
creator_list = [x for x in files_list if x.endswith(
'.py') and x not in constants.MODEL_LIST[args.model]['exclude_list']]
for creator_file in creator_list:
print(f'testing on {creator_file}')
creator, available_parameters = generate_parameters(creator_file)
for solver in constants.MODEL_LIST[args.model]['solver_list']:
print(f'testing with {solver}')
for parameters in available_parameters:
number_of_rounds = 1
max_time = 0.0
while True:
number_of_rounds += 1
if max_time > 2.0 and number_of_rounds > 6:
break
if not os.path.exists(f'scripts/task_1_easy_results/{args.model}/results_{number_of_rounds}.csv'):
with open(f'scripts/task_1_easy_results/{args.model}/results_{number_of_rounds}.csv', 'a') as table:
newline = [
'Cipher',
'Model',
'Building time',
'Solving time',
'Memory',
'Weight',
'Solver']
writer(table).writerow(newline)
with open(f'scripts/task_1_easy_results/{args.model}/results_{number_of_rounds}.csv', 'a') as table:
parameters['number_of_rounds'] = number_of_rounds
if creator_file in [failure[0] for failure in failure_queue[solver]]:
break
cipher = creator(**parameters)
fixed_variables = generate_fixed_variables(cipher)
if args.model == 'cp':
module = import_module(
f'claasp.cipher_modules.models.{args.model}.{args.model}_models'
f'.{args.model}_xor_differential_trail_search_model')
model_capitalised = args.model.capitalize()
model_class = getattr(module, f'{model_capitalised}XorDifferentialTrailSearchModel')
else:
module = import_module(
f'claasp.cipher_modules.models.{args.model}.{args.model}_models'
f'.{args.model}_xor_differential_model')
model_capitalised = args.model.capitalize()
model_class = getattr(module, f'{model_capitalised}XorDifferentialModel')
model = model_class(cipher)
solution = timeout(model.find_lowest_weight_xor_differential_trail, (fixed_variables, solver))
if isinstance(solution, str):
print(f'{creator_file} failed on {parameters["number_of_rounds"]}')
failure_queue[solver].append([creator_file, parameters])
break
build_time, solve_time, memory, weight = handle_solution(solution)
max_time = build_time + solve_time
newline = [model.cipher_id, model.__class__.__name__,
build_time, solve_time, memory, weight, solver]
print(newline)
writer(table).writerow(newline)
print(f'STARTING SECOND PHASE FOR {args.model}')
for i in range(3):
end_time = 600 * 2 ** (i + 1)
print(f'current end_time on {args.model} = {end_time}')
for solver in constants.MODEL_LIST[args.model]['solver_list']:
for creator_file, parameters in failure_queue[solver]:
print('testing on couple ', end='')
print([creator_file, parameters], end='')
print(' with ' + solver)
creator = generate_parameters(creator_file)[0]
for number_of_rounds in range(parameters['number_of_rounds'], 7):
parameters['number_of_rounds'] = number_of_rounds
cipher = creator(**parameters)
fixed_variables = generate_fixed_variables(cipher)
if args.model == 'cp':
module = import_module(
f'claasp.cipher_modules.models.{args.model}.{args.model}_models'
f'.{args.model}_xor_differential_trail_search_model')
model_capitalised = args.model.capitalize()
model_class = getattr(module, f'{model_capitalised}XorDifferentialTrailSearchModel')
else:
module = import_module(
f'claasp.cipher_modules.models.{args.model}.{args.model}_models'
f'.{args.model}_xor_differential_model')
model_capitalised = args.model.capitalize()
model_class = getattr(module, f'{model_capitalised}XorDifferentialModel')
model = model_class(cipher)
solution = timeout(model.find_lowest_weight_xor_differential_trail,
(fixed_variables, solver), timeout_duration=end_time)
if not isinstance(solution, str):
print(f'{creator_file} succeeded on {number_of_rounds}')
if [creator_file, parameters] in failure_queue[solver]:
failure_queue[solver].remove([creator_file, parameters])
if isinstance(solution, str) and ([creator_file, parameters] not in failure_queue[solver]):
failure_queue[solver].append([creator_file, parameters])
print(f'{creator_file} failed on {number_of_rounds}')
break
if isinstance(solution, str) and ([creator_file, parameters] in failure_queue[solver]):
print(f'{creator_file} failed again on {number_of_rounds}')
break
build_time, solve_time, memory, weight = handle_solution(solution)
newline = [
model.cipher_id,
model.__class__.__name__,
build_time,
solve_time,
memory,
weight,
solver]
print(newline)
with open(f'scripts/task_1_easy_results/{args.model}/results_{number_of_rounds}.csv', 'a') as table:
writer(table).writerow(newline)