├── aes_cipher ├── __init__.py ├── aes.py ├── aes_s_box_tester.py ├── aes_t_table_tester.py ├── aes_tester.py ├── key_schedule.py ├── encryption_t_table.py ├── encryption_s_box.py └── constants.py ├── plotter ├── __init__.py ├── output │ └── .gitignore └── plot_results.py ├── settings ├── __init__.py ├── settings.ini └── active_settings.py ├── cpa_attacker ├── __init__.py ├── data │ └── .gitignore ├── output │ └── .gitignore ├── plotter.py ├── round1.py └── attacker.py ├── hw_distribution ├── __init__.py ├── output │ └── .gitignore ├── s_box_hw_distribution.py └── t_table_hw_distribution.py ├── leakage_model ├── __init__.py ├── hw_s_box.py └── hw_t_table.py ├── expected_round_keys ├── __init__.py └── expected_round_keys_generator.py ├── leakage_generator ├── __init__.py ├── data │ └── .gitignore ├── leaking_encryption_s_box.py ├── leaking_encryption_t_table.py └── generator.py ├── symbolic_evaluator ├── __init__.py ├── data │ └── .gitignore └── evaluation_case_solver.py ├── correlation_coefficient_difference ├── __init__.py └── delta_simulator.py ├── run.py ├── README.md ├── .gitignore └── LICENSE /aes_cipher/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /plotter/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /settings/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cpa_attacker/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /hw_distribution/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /leakage_model/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /expected_round_keys/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /leakage_generator/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /symbolic_evaluator/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /correlation_coefficient_difference/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cpa_attacker/data/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | * 3 | 4 | # But not these files... 5 | !.gitignore -------------------------------------------------------------------------------- /plotter/output/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | * 3 | 4 | # But not these files... 5 | !.gitignore -------------------------------------------------------------------------------- /cpa_attacker/output/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | * 3 | 4 | # But not these files... 5 | !.gitignore -------------------------------------------------------------------------------- /hw_distribution/output/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | * 3 | 4 | # But not these files... 5 | !.gitignore -------------------------------------------------------------------------------- /leakage_generator/data/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | * 3 | 4 | # But not these files... 5 | !.gitignore -------------------------------------------------------------------------------- /symbolic_evaluator/data/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | * 3 | 4 | # But not these files... 5 | !.gitignore -------------------------------------------------------------------------------- /settings/settings.ini: -------------------------------------------------------------------------------- 1 | [AES] 2 | # key - hexadecimal value 3 | key = 0xf530357968578480b398a3c251cd1093 4 | # key = 0x52bd2f944bc82d6607bd86412b587a43 5 | 6 | 7 | # radom state - list of bytes in hexadecimal 8 | random_state = [0x16, 0x2d, 0xb1, 0x0a, 0x22, 0x2c, 0x68, 0x88, 0x7d, 0x43, 0x42, 0x2c, 0x61, 0xc2, 0xe5, 0x5a] 9 | # random_state = [0xb6, 0xfd, 0x28, 0xdd, 0xa9, 0xfd, 0xba, 0x58, 0x50, 0xf3, 0xb1, 0x92, 0x93, 0x25, 0xce, 0x95] 10 | -------------------------------------------------------------------------------- /aes_cipher/aes.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.key_schedule import KeySchedule 2 | from aes_cipher.encryption_s_box import EncryptionSBox 3 | 4 | 5 | class Aes: 6 | def __init__(self, key): 7 | self.key = key 8 | 9 | self.key_schedule = KeySchedule() 10 | self.round_keys = self.key_schedule.run(self.key) 11 | 12 | self.encryption = EncryptionSBox(self.round_keys) 13 | 14 | def encrypt(self, plaintext): 15 | return self.encryption.encrypt(plaintext) 16 | -------------------------------------------------------------------------------- /leakage_model/hw_s_box.py: -------------------------------------------------------------------------------- 1 | class HwSBox: 2 | def __init__(self): 3 | self.hw_table_length = 2 ** 8 4 | self.hw_table = [0] * self.hw_table_length 5 | 6 | self.init_hw_table() 7 | 8 | @staticmethod 9 | def hw(value): 10 | return bin(value).count('1') 11 | 12 | def init_hw_table(self): 13 | for i in range(self.hw_table_length): 14 | self.hw_table[i] = self.hw(i) 15 | 16 | def leak(self, value): 17 | return self.hw_table[value] 18 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | from cpa_attacker.attacker import Attacker 2 | 3 | 4 | import os 5 | import time 6 | 7 | 8 | def main(): 9 | os.chdir('./cpa_attacker/') 10 | 11 | attacker = Attacker(generate_traces=True, t_tables_implementation=True, debug=False) 12 | attacker.attack_guessing_entropy_evaluation_cases() 13 | 14 | 15 | if "__main__" == __name__: 16 | start_time = time.time() 17 | 18 | main() 19 | 20 | stop_time = time.time() 21 | 22 | print('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(stop_time - start_time)))) 23 | -------------------------------------------------------------------------------- /leakage_model/hw_t_table.py: -------------------------------------------------------------------------------- 1 | class HwTTable: 2 | def __init__(self): 3 | self.hw_table_length = 2 ** 16 4 | self.hw_table = [0] * self.hw_table_length 5 | 6 | self.init_hw_table() 7 | 8 | @staticmethod 9 | def hw(value): 10 | return bin(value).count('1') 11 | 12 | def init_hw_table(self): 13 | for i in range(self.hw_table_length): 14 | self.hw_table[i] = self.hw(i) 15 | 16 | def leak(self, value): 17 | return self.hw_table[value & 0xffff] + self.hw_table[value >> 16 & 0xffff] 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aes-cpa 2 | This repository includes the software artifacts used for our paper: 3 | > Alex Biryukov, Daniel Dinu, and Yann Le Corre, 4 | > [Side-Channel Attacks meet Secure Network Protocols][paper], 5 | > ACNS 2017 6 | 7 | ## Description 8 | Features: 9 | * symbolic processing of an initial state 10 | * CPA attack on a given evaluation case 11 | 12 | The source code can be used to attack two implementations of the AES: 13 | * S-box implementation 14 | * T-table implementation 15 | 16 | For details, read [our paper][paper] or have a look at the source code. 17 | 18 | ## Required Packages 19 | * matplotlib 20 | * numpy 21 | 22 | ## Acknowledgement 23 | This work is supported by the CORE project ACRYPT (ID C12-15-4009992) funded by 24 | the [Fonds National de la Recherche, Luxembourg][fnr]. 25 | 26 | [paper]: http://orbilu.uni.lu/bitstream/10993/31797/1/ACNS2017.pdf 27 | [fnr]: https://www.fnr.lu/ 28 | -------------------------------------------------------------------------------- /aes_cipher/aes_s_box_tester.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.key_schedule import KeySchedule 2 | from aes_cipher.encryption_s_box import EncryptionSBox 3 | from aes_cipher.aes_tester import AesTester 4 | 5 | 6 | import time 7 | 8 | 9 | class AesSBoxTester(AesTester): 10 | def __init__(self, key=None): 11 | super().__init__() 12 | self.key_schedule = KeySchedule() 13 | self.encryption = EncryptionSBox() 14 | self.key = key 15 | 16 | 17 | def main(): 18 | tester = AesSBoxTester() 19 | tests = [ 20 | (0xf530357968578480b398a3c251cd1093, 0x00, 0xf5df39990fc688f1b07224cc03e86cea), 21 | (0x2b7e151628aed2a6abf7158809cf4f3c, 0x3243f6a8885a308d313198a2e0370734, 0x3925841d02dc09fbdc118597196a0b32) 22 | ] 23 | tester.run_tests(tests) 24 | 25 | 26 | if "__main__" == __name__: 27 | start_time = time.time() 28 | 29 | main() 30 | 31 | stop_time = time.time() 32 | 33 | print('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(stop_time - start_time)))) 34 | -------------------------------------------------------------------------------- /aes_cipher/aes_t_table_tester.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.key_schedule import KeySchedule 2 | from aes_cipher.encryption_t_table import EncryptionTTable 3 | from aes_cipher.aes_tester import AesTester 4 | 5 | 6 | import time 7 | 8 | 9 | class AesTTableTester(AesTester): 10 | def __init__(self, key=None): 11 | super().__init__() 12 | self.key_schedule = KeySchedule() 13 | self.encryption = EncryptionTTable() 14 | self.key = key 15 | 16 | 17 | def main(): 18 | tester = AesTTableTester() 19 | tests = [ 20 | (0xf530357968578480b398a3c251cd1093, 0x00, 0xf5df39990fc688f1b07224cc03e86cea), 21 | (0x2b7e151628aed2a6abf7158809cf4f3c, 0x3243f6a8885a308d313198a2e0370734, 0x3925841d02dc09fbdc118597196a0b32) 22 | ] 23 | tester.run_tests(tests) 24 | 25 | 26 | if "__main__" == __name__: 27 | start_time = time.time() 28 | 29 | main() 30 | 31 | stop_time = time.time() 32 | 33 | print('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(stop_time - start_time)))) 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # Ipython Notebook 62 | .ipynb_checkpoints 63 | 64 | # PyCharm 65 | .idea/ 66 | -------------------------------------------------------------------------------- /leakage_generator/leaking_encryption_s_box.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.encryption_s_box import EncryptionSBox 2 | from aes_cipher.constants import s_box 3 | from leakage_model.hw_s_box import HwSBox 4 | 5 | 6 | import numpy 7 | 8 | 9 | class LeakingEncryptionSBox(EncryptionSBox): 10 | def __init__(self, round_keys): 11 | EncryptionSBox.__init__(self, round_keys) 12 | self.number_of_samples = 16 * 10 13 | 14 | self.leakage = None 15 | self.leakage_index = 0 16 | 17 | self.power_model = HwSBox() 18 | 19 | def sub_bytes(self): 20 | for i in range(16): 21 | self.state[i] = s_box[self.state[i]] 22 | 23 | self.leakage[self.leakage_index] = self.power_model.leak(self.state[i]) 24 | self.leakage_index += 1 25 | 26 | def encrypt(self, plaintext): 27 | self.leakage = numpy.zeros(self.number_of_samples) 28 | self.leakage_index = 0 29 | 30 | self.set_state(plaintext) 31 | 32 | self.add_round_key() 33 | 34 | for round_number in range(1, 10, 1): 35 | self.encrypt_round(round_number) 36 | self.encrypt_last_round(10) 37 | 38 | return self.leakage 39 | -------------------------------------------------------------------------------- /settings/active_settings.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | import os 3 | 4 | 5 | class ActiveSettings: 6 | instance = None 7 | 8 | def __new__(cls, *args, **kwargs): 9 | if not cls.instance: 10 | cls.instance = super(ActiveSettings, cls).__new__(cls, *args, **kwargs) 11 | 12 | cls.instance.key = 0x00 13 | cls.instance.random_state = [0] * 16 14 | 15 | working_dir = os.getcwd() 16 | package_dir = os.path.dirname(os.path.dirname(__file__)) 17 | configuration_file = os.path.join(os.path.relpath(package_dir, working_dir), 'settings/settings.ini') 18 | 19 | try: 20 | config_parser = configparser.ConfigParser() 21 | config_parser.read(configuration_file) 22 | 23 | key = config_parser.get('AES', 'key') 24 | cls.instance.key = int(key, 16) 25 | 26 | random_state = config_parser.get('AES', 'random_state') 27 | cls.instance.random_state = list(map(lambda it: int(it.strip('[ ]'), 16), random_state.split(','))) 28 | except Exception as e: 29 | print('ERROR in {}: {}!'.format(cls.instance.__class__.__name__, e)) 30 | 31 | return cls.instance 32 | 33 | 34 | def main(): 35 | active_settings = ActiveSettings() 36 | print('Active settings') 37 | print('-' * 15) 38 | 39 | print('key 0x{}'.format(format(active_settings.key, '032x'))) 40 | 41 | print('random_state [', end='') 42 | length = len(active_settings.random_state) - 1 43 | for i in range(length): 44 | print('0x{}, '.format(format(active_settings.random_state[i], '02x')), end='') 45 | print('0x{}] '.format(format(active_settings.random_state[length], '02x')), end='') 46 | 47 | 48 | if "__main__" == __name__: 49 | main() 50 | -------------------------------------------------------------------------------- /aes_cipher/aes_tester.py: -------------------------------------------------------------------------------- 1 | class AesTester: 2 | def __init__(self): 3 | self.key_schedule = None 4 | self.encryption = None 5 | self.key = None 6 | 7 | def test_key_schedule(self): 8 | self.key_schedule.run(self.key) 9 | 10 | for i in range(11): 11 | print('{:2}: '.format(i), end='') 12 | for j in range(16): 13 | print('{} '.format(format(self.key_schedule.round_keys[i][j], '02x')), end='') 14 | print() 15 | 16 | def test_encryption(self, plaintext, expected_ciphertext): 17 | self.key_schedule.run(self.key) 18 | 19 | self.encryption.set_round_keys(self.key_schedule.round_keys) 20 | ciphertext = self.encryption.encrypt(plaintext) 21 | 22 | print('ciphertext = {} '.format(format(ciphertext, '032x')), end='') 23 | if expected_ciphertext == ciphertext: 24 | print('OK!') 25 | else: 26 | print('WRONG!') 27 | 28 | def get_round_keys(self): 29 | self.key_schedule.run(self.key) 30 | 31 | for i in range(11): 32 | print('{:2}: '.format(i), end='') 33 | print('[ ', end='') 34 | for j in range(15): 35 | print('0x{}, '.format(format(self.key_schedule.round_keys[i][j], '02x')), end='') 36 | print('0x{} '.format(format(self.key_schedule.round_keys[i][15], '02x')), end='') 37 | print(']', end='') 38 | print() 39 | 40 | def run(self, key, plaintext, expected_ciphertext): 41 | self.key = key 42 | 43 | self.test_key_schedule() 44 | print() 45 | self.test_encryption(plaintext, expected_ciphertext) 46 | print() 47 | self.get_round_keys() 48 | print() 49 | 50 | def run_tests(self, tests): 51 | for key, plaintext, ciphertext in tests: 52 | self.run(key, plaintext, ciphertext) 53 | print() 54 | -------------------------------------------------------------------------------- /aes_cipher/key_schedule.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import r_con 2 | from aes_cipher.constants import s_box 3 | 4 | 5 | class KeySchedule: 6 | def __init__(self): 7 | self.key = None 8 | self.round_keys = [[0 for i in range(16)] for i in range(11)] 9 | 10 | def run(self, key): 11 | self.key = key 12 | 13 | for i in range(16): 14 | self.round_keys[0][i] = (key >> 8 * (15 - i)) & 0xff 15 | 16 | for i in range(1, 11, 1): 17 | self.round_keys[i][0] = self.round_keys[i - 1][0] ^ r_con[i - 1] ^ s_box[self.round_keys[i - 1][13]] 18 | self.round_keys[i][1] = self.round_keys[i - 1][1] ^ s_box[self.round_keys[i - 1][14]] 19 | self.round_keys[i][2] = self.round_keys[i - 1][2] ^ s_box[self.round_keys[i - 1][15]] 20 | self.round_keys[i][3] = self.round_keys[i - 1][3] ^ s_box[self.round_keys[i - 1][12]] 21 | 22 | self.round_keys[i][4] = self.round_keys[i - 1][4] ^ self.round_keys[i][0] 23 | self.round_keys[i][5] = self.round_keys[i - 1][5] ^ self.round_keys[i][1] 24 | self.round_keys[i][6] = self.round_keys[i - 1][6] ^ self.round_keys[i][2] 25 | self.round_keys[i][7] = self.round_keys[i - 1][7] ^ self.round_keys[i][3] 26 | 27 | self.round_keys[i][8] = self.round_keys[i - 1][8] ^ self.round_keys[i][4] 28 | self.round_keys[i][9] = self.round_keys[i - 1][9] ^ self.round_keys[i][5] 29 | self.round_keys[i][10] = self.round_keys[i - 1][10] ^ self.round_keys[i][6] 30 | self.round_keys[i][11] = self.round_keys[i - 1][11] ^ self.round_keys[i][7] 31 | 32 | self.round_keys[i][12] = self.round_keys[i - 1][12] ^ self.round_keys[i][8] 33 | self.round_keys[i][13] = self.round_keys[i - 1][13] ^ self.round_keys[i][9] 34 | self.round_keys[i][14] = self.round_keys[i - 1][14] ^ self.round_keys[i][10] 35 | self.round_keys[i][15] = self.round_keys[i - 1][15] ^ self.round_keys[i][11] 36 | 37 | return self.round_keys 38 | -------------------------------------------------------------------------------- /leakage_generator/leaking_encryption_t_table.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.encryption_t_table import EncryptionTTable 2 | from aes_cipher.constants import t0, t1, t2, t3 3 | from leakage_model.hw_t_table import HwTTable 4 | 5 | 6 | import numpy 7 | 8 | 9 | class LeakingEncryptionTTable(EncryptionTTable): 10 | def __init__(self, round_keys): 11 | EncryptionTTable.__init__(self, round_keys) 12 | self.number_of_samples = 16 * 10 13 | 14 | self.leakage = None 15 | self.leakage_index = 0 16 | 17 | self.power_model = HwTTable() 18 | 19 | def t_table_lookup(self): 20 | c0 = t0[self.state[0]] ^ t1[self.state[5]] ^ t2[self.state[10]] ^ t3[self.state[15]] 21 | c1 = t0[self.state[4]] ^ t1[self.state[9]] ^ t2[self.state[14]] ^ t3[self.state[3]] 22 | c2 = t0[self.state[8]] ^ t1[self.state[13]] ^ t2[self.state[2]] ^ t3[self.state[7]] 23 | c3 = t0[self.state[12]] ^ t1[self.state[1]] ^ t2[self.state[6]] ^ t3[self.state[11]] 24 | 25 | for i in range(16): 26 | if 0 == i % 4: 27 | value = t0[self.state[i]] 28 | elif 1 == i % 4: 29 | value = t1[self.state[i]] 30 | elif 2 == i % 4: 31 | value = t2[self.state[i]] 32 | elif 3 == i % 4: 33 | value = t3[self.state[i]] 34 | 35 | self.leakage[self.leakage_index] = self.power_model.leak(value) 36 | self.leakage_index += 1 37 | 38 | self.state[0] = (c0 >> 24) & 0xff 39 | self.state[1] = (c0 >> 16) & 0xff 40 | self.state[2] = (c0 >> 8) & 0xff 41 | self.state[3] = (c0 >> 0) & 0xff 42 | 43 | self.state[4] = (c1 >> 24) & 0xff 44 | self.state[5] = (c1 >> 16) & 0xff 45 | self.state[6] = (c1 >> 8) & 0xff 46 | self.state[7] = (c1 >> 0) & 0xff 47 | 48 | self.state[8] = (c2 >> 24) & 0xff 49 | self.state[9] = (c2 >> 16) & 0xff 50 | self.state[10] = (c2 >> 8) & 0xff 51 | self.state[11] = (c2 >> 0) & 0xff 52 | 53 | self.state[12] = (c3 >> 24) & 0xff 54 | self.state[13] = (c3 >> 16) & 0xff 55 | self.state[14] = (c3 >> 8) & 0xff 56 | self.state[15] = (c3 >> 0) & 0xff 57 | 58 | def encrypt(self, plaintext): 59 | self.leakage = numpy.zeros(self.number_of_samples) 60 | self.leakage_index = 0 61 | 62 | self.set_state(plaintext) 63 | 64 | self.add_round_key() 65 | 66 | for round_number in range(1, 10, 1): 67 | self.encrypt_round(round_number) 68 | self.encrypt_last_round(10) 69 | 70 | return self.leakage 71 | -------------------------------------------------------------------------------- /leakage_generator/generator.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.key_schedule import KeySchedule 2 | from leakage_generator.leaking_encryption_s_box import LeakingEncryptionSBox 3 | from leakage_generator.leaking_encryption_t_table import LeakingEncryptionTTable 4 | from settings.active_settings import ActiveSettings 5 | 6 | 7 | import copy 8 | import numpy 9 | import pickle 10 | import random 11 | 12 | 13 | class Generator: 14 | def __init__(self, state, number_of_traces=1000, t_tables_implementation=False): 15 | self.number_of_samples = 16 * 10 16 | 17 | active_settings = ActiveSettings() 18 | self.key = active_settings.key 19 | self.random_state = active_settings.random_state 20 | 21 | self.traces_file = './data/traces.npy' 22 | self.plaintexts_file = './data/plaintexts.bin' 23 | self.number_of_traces = number_of_traces 24 | 25 | self.state = copy.deepcopy(state[0]) 26 | 27 | for i in range(16): 28 | if 0 != self.state[i]: 29 | self.state[i] = 0xff 30 | 31 | self.t_tables_implementation = t_tables_implementation 32 | 33 | def init_leaking_aes(self): 34 | key_schedule = KeySchedule() 35 | key_schedule.run(self.key) 36 | 37 | if self.t_tables_implementation: 38 | return LeakingEncryptionTTable(key_schedule.round_keys) 39 | return LeakingEncryptionSBox(key_schedule.round_keys) 40 | 41 | def get_plaintext(self): 42 | plaintext = 0 43 | 44 | for i in range(16): 45 | plaintext <<= 8 46 | 47 | # 1. Fill with zeros 48 | # plaintext += random.getrandbits(8) & self.state[i] 49 | 50 | # 2. Fill with random values 51 | # ''' 52 | if self.state[i]: 53 | plaintext += random.getrandbits(8) 54 | else: 55 | plaintext += self.random_state[i] 56 | # ''' 57 | 58 | return plaintext 59 | 60 | def generate(self): 61 | leaking_encryption = self.init_leaking_aes() 62 | 63 | traces = numpy.zeros((self.number_of_traces, self.number_of_samples)) 64 | plaintexts = [0] * self.number_of_traces 65 | 66 | for i in range(self.number_of_traces): 67 | plaintexts[i] = self.get_plaintext() 68 | traces[i] = leaking_encryption.encrypt(plaintexts[i]) 69 | 70 | numpy.save(self.traces_file, traces) 71 | 72 | f = open(self.plaintexts_file, 'wb') 73 | pickle.dump(plaintexts, f) 74 | f.close() 75 | 76 | 77 | def main(): 78 | generator = Generator([[1] * 16]) 79 | generator.generate() 80 | 81 | 82 | if "__main__" == __name__: 83 | main() 84 | -------------------------------------------------------------------------------- /cpa_attacker/plotter.py: -------------------------------------------------------------------------------- 1 | import matplotlib 2 | import matplotlib.pyplot 3 | 4 | 5 | class Plotter: 6 | def __init__(self): 7 | # Force matplotlib to not use any Xwindows backend. 8 | # Details: http://stackoverflow.com/questions/2801882/generating-a-png-with-matplotlib-when-display-is-undefined 9 | matplotlib.use('Agg') 10 | 11 | @staticmethod 12 | def plot_correlation_matrix(correlation_matrix, index, expected_key, possible_key_count): 13 | for i in range(correlation_matrix.shape[0]): 14 | matplotlib.pyplot.plot(correlation_matrix[i], 'g') 15 | 16 | matplotlib.pyplot.plot(correlation_matrix[expected_key], 'r') 17 | 18 | matplotlib.pyplot.title('Correlation Matrix') 19 | matplotlib.pyplot.xlabel('Sample') 20 | matplotlib.pyplot.ylabel('Correlation') 21 | 22 | axes = matplotlib.pyplot.gca() 23 | axes.set_xlim(0, correlation_matrix.shape[1]) 24 | 25 | correlation_matrix_file = 'output/CM_{:02}_{}.png'.format(index, possible_key_count) 26 | matplotlib.pyplot.savefig(correlation_matrix_file, bbox_inches='tight') 27 | matplotlib.pyplot.close() 28 | 29 | @staticmethod 30 | def plot_guessing_entropy(title, x_traces, y_guessing_entropy): 31 | Plotter.plot_guessing_entropy_short(title, x_traces, y_guessing_entropy) 32 | Plotter.plot_guessing_entropy_long(title, x_traces, y_guessing_entropy) 33 | 34 | @staticmethod 35 | def plot_guessing_entropy_short(title, x_traces, y_guessing_entropy): 36 | matplotlib.pyplot.plot(x_traces, y_guessing_entropy, linewidth=2.0, color='r', marker='x', markersize=10) 37 | matplotlib.pyplot.axhline(y=0, color='k', ls='dashed') 38 | 39 | # matplotlib.pyplot.title('GE - {}'.format(title)) 40 | matplotlib.pyplot.xlabel('Traces') 41 | matplotlib.pyplot.ylabel('GE') 42 | 43 | axes = matplotlib.pyplot.gca() 44 | axes.set_ylim([-1, 10]) 45 | 46 | matplotlib.pyplot.savefig('./output/GE_short_{}.png'.format(title), bbox_inches='tight') 47 | matplotlib.pyplot.close() 48 | 49 | @staticmethod 50 | def plot_guessing_entropy_long(title, x_traces, y_guessing_entropy): 51 | matplotlib.pyplot.plot(x_traces, y_guessing_entropy, linewidth=2.0, color='r', marker='x', markersize=10) 52 | matplotlib.pyplot.axhline(y=0, color='k', ls='dashed') 53 | 54 | # matplotlib.pyplot.title('GE - {}'.format(title)) 55 | matplotlib.pyplot.xlabel('Traces') 56 | matplotlib.pyplot.ylabel('GE') 57 | 58 | axes = matplotlib.pyplot.gca() 59 | axes.set_ylim([-1, 128]) 60 | 61 | matplotlib.pyplot.savefig('./output/GE_long_{}.png'.format(title), bbox_inches='tight') 62 | matplotlib.pyplot.close() 63 | -------------------------------------------------------------------------------- /hw_distribution/s_box_hw_distribution.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import s_box 2 | from leakage_model.hw_s_box import HwSBox 3 | 4 | 5 | import matplotlib.pyplot 6 | import numpy 7 | import time 8 | 9 | 10 | class SBoxHwDistribution: 11 | def __init__(self): 12 | self.power_model = HwSBox() 13 | 14 | self.input_size = 8 15 | self.output_size = 8 16 | 17 | self.hw_distribution = None 18 | 19 | def get_key_distribution(self, key): 20 | self.hw_distribution = [0 for i in range(self.output_size + 1)] 21 | 22 | for i in range(2 ** self.input_size): 23 | intermediate = s_box[i ^ key] 24 | power = self.power_model.leak(intermediate) 25 | self.hw_distribution[power] += 1 26 | 27 | return self.hw_distribution 28 | 29 | def get_distribution(self): 30 | self.hw_distribution = [0 for i in range(self.output_size + 1)] 31 | 32 | for k in range(2 ** self.input_size): 33 | for i in range(2 ** self.input_size): 34 | intermediate = s_box[i ^ k] 35 | power = self.power_model.leak(intermediate) 36 | self.hw_distribution[power] += 1 37 | 38 | return self.hw_distribution 39 | 40 | @property 41 | def is_symmetric(self): 42 | for i in range(self.output_size // 2): 43 | if self.hw_distribution[i] != self.hw_distribution[self.output_size - i]: 44 | return False 45 | return True 46 | 47 | def plot(self, title): 48 | number_of_values = len(self.hw_distribution) 49 | 50 | matplotlib.pyplot.bar(numpy.arange(number_of_values), self.hw_distribution, width=0.5, align='center') 51 | 52 | axes = matplotlib.pyplot.gca() 53 | axes.set_xlim([-1, number_of_values]) 54 | matplotlib.pyplot.xticks(numpy.arange(0, number_of_values, 1)) 55 | 56 | matplotlib.pyplot.savefig('./output/{}.png'.format(title)) 57 | matplotlib.pyplot.close() 58 | 59 | def print_distribution(self): 60 | print('Distribution') 61 | print('=' * 12) 62 | 63 | for i in range(self.output_size + 1): 64 | print('{}: {}'.format(i, self.hw_distribution[i])) 65 | 66 | print('-' * 12) 67 | 68 | def generate(self): 69 | self.get_distribution() 70 | self.plot('s_box') 71 | 72 | self.print_distribution() 73 | print('Symmetric: {}'.format(self.is_symmetric)) 74 | 75 | 76 | def main(): 77 | distribution = SBoxHwDistribution() 78 | distribution.generate() 79 | 80 | 81 | if "__main__" == __name__: 82 | start_time = time.time() 83 | 84 | main() 85 | 86 | stop_time = time.time() 87 | 88 | print('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(stop_time - start_time)))) 89 | -------------------------------------------------------------------------------- /hw_distribution/t_table_hw_distribution.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import t0, t1, t2, t3 2 | from leakage_model.hw_t_table import HwTTable 3 | 4 | 5 | import matplotlib.pyplot 6 | import numpy 7 | import time 8 | 9 | 10 | class TTableHwDistribution: 11 | def __init__(self, table_index=0): 12 | self.power_model = HwTTable() 13 | 14 | self.input_size = 8 15 | self.output_size = 32 16 | 17 | self.hw_distribution = None 18 | 19 | self.table = None 20 | self.init_table(table_index) 21 | 22 | def init_table(self, index): 23 | if 0 == index: 24 | self.table = t0 25 | elif 1 == index: 26 | self.table = t1 27 | elif 2 == index: 28 | self.table = t2 29 | elif 3 == index: 30 | self.table = t3 31 | 32 | def get_key_distribution(self, key): 33 | self.hw_distribution = [0 for i in range(self.output_size + 1)] 34 | 35 | for i in range(2 ** self.input_size): 36 | intermediate = self.table[i ^ key] 37 | power = self.power_model.leak(intermediate) 38 | self.hw_distribution[power] += 1 39 | 40 | return self.hw_distribution 41 | 42 | def get_distribution(self): 43 | self.hw_distribution = [0 for i in range(self.output_size + 1)] 44 | 45 | for k in range(2 ** self.input_size): 46 | for i in range(2 ** self.input_size): 47 | intermediate = self.table[i ^ k] 48 | power = self.power_model.leak(intermediate) 49 | self.hw_distribution[power] += 1 50 | 51 | return self.hw_distribution 52 | 53 | @property 54 | def is_symmetric(self): 55 | for i in range(self.output_size // 2): 56 | if self.hw_distribution[i] != self.hw_distribution[self.output_size - i]: 57 | return False 58 | return True 59 | 60 | def plot(self, title): 61 | number_of_values = len(self.hw_distribution) 62 | 63 | matplotlib.pyplot.bar(numpy.arange(number_of_values), self.hw_distribution, width=0.5, align='center') 64 | 65 | axes = matplotlib.pyplot.gca() 66 | axes.set_xlim([-1, number_of_values]) 67 | matplotlib.pyplot.xticks(numpy.arange(0, number_of_values, 2)) 68 | 69 | matplotlib.pyplot.savefig('./output/{}.png'.format(title)) 70 | matplotlib.pyplot.close() 71 | 72 | def print_distribution(self, index): 73 | print('Distribution T{}'.format(index)) 74 | print('=' * 15) 75 | 76 | for i in range(self.output_size + 1): 77 | print('{}: {}'.format(i, self.hw_distribution[i])) 78 | 79 | print('-' * 15) 80 | 81 | def generate(self): 82 | for i in range(4): 83 | self.init_table(i) 84 | self.get_distribution() 85 | self.plot('t_table_{}'.format(i)) 86 | 87 | self.print_distribution(i) 88 | print('Symmetric: {}'.format(self.is_symmetric)) 89 | print() 90 | 91 | 92 | def main(): 93 | distribution = TTableHwDistribution() 94 | distribution.generate() 95 | 96 | 97 | if "__main__" == __name__: 98 | start_time = time.time() 99 | 100 | main() 101 | 102 | stop_time = time.time() 103 | 104 | print('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(stop_time - start_time)))) 105 | -------------------------------------------------------------------------------- /aes_cipher/encryption_t_table.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import s_box, t0, t1, t2, t3 2 | 3 | 4 | class EncryptionTTable: 5 | def __init__(self, round_keys=None): 6 | self.round_keys = round_keys 7 | self.state = [0] * 16 8 | 9 | def set_round_keys(self, round_keys): 10 | self.round_keys = round_keys 11 | 12 | def add_round_key(self, round_number=0): 13 | for i in range(16): 14 | self.state[i] ^= self.round_keys[round_number][i] 15 | 16 | def sub_bytes(self): 17 | for i in range(16): 18 | self.state[i] = s_box[self.state[i]] 19 | 20 | def shift_rows(self): 21 | # Row 0: no shift 22 | 23 | # Row 1: shift by 1 24 | temp_1 = self.state[1] 25 | self.state[1] = self.state[5] 26 | self.state[5] = self.state[9] 27 | self.state[9] = self.state[13] 28 | self.state[13] = temp_1 29 | 30 | # Row 2: shift by 2 31 | temp_1 = self.state[2] 32 | temp_2 = self.state[6] 33 | self.state[2] = self.state[10] 34 | self.state[6] = self.state[14] 35 | self.state[10] = temp_1 36 | self.state[14] = temp_2 37 | 38 | # Row 3: shift by 3 39 | temp_1 = self.state[3] 40 | temp_2 = self.state[7] 41 | temp_3 = self.state[11] 42 | self.state[3] = self.state[15] 43 | self.state[7] = temp_1 44 | self.state[11] = temp_2 45 | self.state[15] = temp_3 46 | 47 | @staticmethod 48 | def multiply(a, b): 49 | p = 0 50 | 51 | for i in range(8): 52 | if 1 == b & 1: 53 | p ^= a 54 | high_bit_set = a & 0x80 55 | a = (a << 1) & 0xff 56 | if 0x80 == high_bit_set: 57 | a ^= 0x1b 58 | b >>= 1 59 | 60 | return p 61 | 62 | def t_table_lookup(self): 63 | c0 = t0[self.state[0]] ^ t1[self.state[5]] ^ t2[self.state[10]] ^ t3[self.state[15]] 64 | c1 = t0[self.state[4]] ^ t1[self.state[9]] ^ t2[self.state[14]] ^ t3[self.state[3]] 65 | c2 = t0[self.state[8]] ^ t1[self.state[13]] ^ t2[self.state[2]] ^ t3[self.state[7]] 66 | c3 = t0[self.state[12]] ^ t1[self.state[1]] ^ t2[self.state[6]] ^ t3[self.state[11]] 67 | 68 | self.state[0] = (c0 >> 24) & 0xff 69 | self.state[1] = (c0 >> 16) & 0xff 70 | self.state[2] = (c0 >> 8) & 0xff 71 | self.state[3] = (c0 >> 0) & 0xff 72 | 73 | self.state[4] = (c1 >> 24) & 0xff 74 | self.state[5] = (c1 >> 16) & 0xff 75 | self.state[6] = (c1 >> 8) & 0xff 76 | self.state[7] = (c1 >> 0) & 0xff 77 | 78 | self.state[8] = (c2 >> 24) & 0xff 79 | self.state[9] = (c2 >> 16) & 0xff 80 | self.state[10] = (c2 >> 8) & 0xff 81 | self.state[11] = (c2 >> 0) & 0xff 82 | 83 | self.state[12] = (c3 >> 24) & 0xff 84 | self.state[13] = (c3 >> 16) & 0xff 85 | self.state[14] = (c3 >> 8) & 0xff 86 | self.state[15] = (c3 >> 0) & 0xff 87 | 88 | def encrypt_round(self, round_number): 89 | self.t_table_lookup() 90 | self.add_round_key(round_number) 91 | 92 | def encrypt_last_round(self, round_number): 93 | self.sub_bytes() 94 | self.shift_rows() 95 | self.add_round_key(round_number) 96 | 97 | def set_state(self, plaintext): 98 | for i in range(16): 99 | self.state[i] = (plaintext >> 8 * (15 - i)) & 0xff 100 | 101 | def get_state(self): 102 | ciphertext = 0 103 | 104 | for i in range(16): 105 | ciphertext <<= 8 106 | ciphertext ^= self.state[i] 107 | 108 | return ciphertext 109 | 110 | def print_state(self): 111 | for i in range(16): 112 | print('{} '.format(format(self.state[i], '02x')), end='') 113 | print() 114 | 115 | def encrypt(self, plaintext): 116 | self.set_state(plaintext) 117 | 118 | self.add_round_key() 119 | 120 | for round_number in range(1, 10, 1): 121 | self.encrypt_round(round_number) 122 | self.encrypt_last_round(10) 123 | 124 | return self.get_state() 125 | -------------------------------------------------------------------------------- /aes_cipher/encryption_s_box.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import s_box 2 | 3 | 4 | class EncryptionSBox: 5 | def __init__(self, round_keys=None): 6 | self.round_keys = round_keys 7 | self.state = [0] * 16 8 | 9 | def set_round_keys(self, round_keys): 10 | self.round_keys = round_keys 11 | 12 | def add_round_key(self, round_number=0): 13 | for i in range(16): 14 | self.state[i] ^= self.round_keys[round_number][i] 15 | 16 | def sub_bytes(self): 17 | for i in range(16): 18 | self.state[i] = s_box[self.state[i]] 19 | 20 | def shift_rows(self): 21 | # Row 0: no shift 22 | 23 | # Row 1: shift by 1 24 | temp_1 = self.state[1] 25 | self.state[1] = self.state[5] 26 | self.state[5] = self.state[9] 27 | self.state[9] = self.state[13] 28 | self.state[13] = temp_1 29 | 30 | # Row 2: shift by 2 31 | temp_1 = self.state[2] 32 | temp_2 = self.state[6] 33 | self.state[2] = self.state[10] 34 | self.state[6] = self.state[14] 35 | self.state[10] = temp_1 36 | self.state[14] = temp_2 37 | 38 | # Row 3: shift by 3 39 | temp_1 = self.state[3] 40 | temp_2 = self.state[7] 41 | temp_3 = self.state[11] 42 | self.state[3] = self.state[15] 43 | self.state[7] = temp_1 44 | self.state[11] = temp_2 45 | self.state[15] = temp_3 46 | 47 | @staticmethod 48 | def multiply(a, b): 49 | p = 0 50 | 51 | for i in range(8): 52 | if 1 == b & 1: 53 | p ^= a 54 | high_bit_set = a & 0x80 55 | a = (a << 1) & 0xff 56 | if 0x80 == high_bit_set: 57 | a ^= 0x1b 58 | b >>= 1 59 | 60 | return p 61 | 62 | def mix_columns(self): 63 | # Column 0 64 | s0 = self.state[0] 65 | s1 = self.state[1] 66 | s2 = self.state[2] 67 | s3 = self.state[3] 68 | 69 | self.state[0] = self.multiply(s0, 2) ^ self.multiply(s1, 3) ^ s2 ^ s3 70 | self.state[1] = s0 ^ self.multiply(s1, 2) ^ self.multiply(s2, 3) ^ s3 71 | self.state[2] = s0 ^ s1 ^ self.multiply(s2, 2) ^ self.multiply(s3, 3) 72 | self.state[3] = self.multiply(s0, 3) ^ s1 ^ s2 ^ self.multiply(s3, 2) 73 | 74 | # Column 1 75 | s0 = self.state[4] 76 | s1 = self.state[5] 77 | s2 = self.state[6] 78 | s3 = self.state[7] 79 | 80 | self.state[4] = self.multiply(s0, 2) ^ self.multiply(s1, 3) ^ s2 ^ s3 81 | self.state[5] = s0 ^ self.multiply(s1, 2) ^ self.multiply(s2, 3) ^ s3 82 | self.state[6] = s0 ^ s1 ^ self.multiply(s2, 2) ^ self.multiply(s3, 3) 83 | self.state[7] = self.multiply(s0, 3) ^ s1 ^ s2 ^ self.multiply(s3, 2) 84 | 85 | # Column 2 86 | s0 = self.state[8] 87 | s1 = self.state[9] 88 | s2 = self.state[10] 89 | s3 = self.state[11] 90 | 91 | self.state[8] = self.multiply(s0, 2) ^ self.multiply(s1, 3) ^ s2 ^ s3 92 | self.state[9] = s0 ^ self.multiply(s1, 2) ^ self.multiply(s2, 3) ^ s3 93 | self.state[10] = s0 ^ s1 ^ self.multiply(s2, 2) ^ self.multiply(s3, 3) 94 | self.state[11] = self.multiply(s0, 3) ^ s1 ^ s2 ^ self.multiply(s3, 2) 95 | 96 | # Column 3 97 | s0 = self.state[12] 98 | s1 = self.state[13] 99 | s2 = self.state[14] 100 | s3 = self.state[15] 101 | 102 | self.state[12] = self.multiply(s0, 2) ^ self.multiply(s1, 3) ^ s2 ^ s3 103 | self.state[13] = s0 ^ self.multiply(s1, 2) ^ self.multiply(s2, 3) ^ s3 104 | self.state[14] = s0 ^ s1 ^ self.multiply(s2, 2) ^ self.multiply(s3, 3) 105 | self.state[15] = self.multiply(s0, 3) ^ s1 ^ s2 ^ self.multiply(s3, 2) 106 | 107 | def encrypt_round(self, round_number): 108 | self.sub_bytes() 109 | self.shift_rows() 110 | self.mix_columns() 111 | self.add_round_key(round_number) 112 | 113 | def encrypt_last_round(self, round_number): 114 | self.sub_bytes() 115 | self.shift_rows() 116 | self.add_round_key(round_number) 117 | 118 | def set_state(self, plaintext): 119 | for i in range(16): 120 | self.state[i] = (plaintext >> 8 * (15 - i)) & 0xff 121 | 122 | def get_state(self): 123 | ciphertext = 0 124 | 125 | for i in range(16): 126 | ciphertext <<= 8 127 | ciphertext ^= self.state[i] 128 | 129 | return ciphertext 130 | 131 | def print_state(self): 132 | for i in range(16): 133 | print('{} '.format(format(self.state[i], '02x')), end='') 134 | print() 135 | 136 | def encrypt(self, plaintext): 137 | self.set_state(plaintext) 138 | 139 | self.add_round_key() 140 | 141 | for round_number in range(1, 10, 1): 142 | self.encrypt_round(round_number) 143 | self.encrypt_last_round(10) 144 | 145 | return self.get_state() 146 | -------------------------------------------------------------------------------- /plotter/plot_results.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | import matplotlib.pyplot 3 | 4 | 5 | # \varphi_1 = S-box selection function 6 | # \varphi_2 = T-table selection function 7 | 8 | # (a) S-box implementation, S-box selection function 9 | # (b) S-box implementation, T-table selection function 10 | # (c) T-table implementation, T-table selection function 11 | # (d) T-table implementation, S-box selection function 12 | 13 | 14 | # Simulated - Implementation - Selection function 15 | # 100 experiments 16 | sim_s_box_s_box = numpy.array([ 17 | 20, 15, 14, 24, 13, 15, 14, 20, 11, 14, 11, 11, 10, 11, 12, 10, 10, 10, 11, 11, 11, 11, 11, 10, 10]) 18 | sim_s_box_t_table = numpy.array([ 19 | 34, 28, 32, 33, 31, 37, 33, 35, 39, 42, 32, 30, 33, 35, 39, 29, 33, 37, 33, 29, 39, 40, 35, 33, 30]) 20 | 21 | sim_t_table_t_table = numpy.array([ 22 | 19, 13, 16, 19, 19, 21, 12, 17, 8, 13, 8, 7, 7, 7, 7, 8, 8, 9, 9, 7, 9, 8, 8, 8, 7]) 23 | sim_t_table_s_box = numpy.array([ 24 | 40, 30, 29, 39, 33, 38, 35, 34, 40, 32, 40, 39, 36, 32, 33, 34, 35, 34, 32, 31, 39, 42, 37, 32, 30]) 25 | 26 | 27 | # Real - Implementation - Selection function 28 | real_s_box_s_box = numpy.array([ 29 | 700, 620, 80, 430, 570, 390, 520, 280, 620, 380, 500, 500, 490, 410, 670, 430, 570, 380, 400, 420, 530, 490, 350, 30 | 510, 240]) 31 | real_s_box_t_table = numpy.array([960, 760, 100, 700, 760, 660, 730, 540, 900, 590, 780, 570, 730, 670, 870, 500, 790, 32 | 560, 590, 650, 910, 620, 670, 650, 310]) 33 | 34 | real_t_table_t_table = numpy.array([ 35 | 630, 600, 180, 790, 300, 820, 390, 790, 910, 800, 800, 640, 660, 1010, 800, 830, 1000, 780, 790, 820, 790, 720, 36 | 640, 810, 590]) 37 | real_t_table_s_box = numpy.array([1120, 490, 80, 1060, 160, 1140, 690, 1290, 1170, 1160, 1190, 1220, 1590, 1240, 1210, 38 | 1150, 1440, 1050, 1420, 990, 1460, 1130, 1200, 1200, 890]) 39 | 40 | 41 | def plot_short(line1, line2, name): 42 | ls_box_phi1 = matplotlib.pyplot.plot(line1, 'ro-') 43 | ls_box_phi2 = matplotlib.pyplot.plot(line2, 'go-') 44 | 45 | axes = matplotlib.pyplot.gca() 46 | axes.set_xlim([0, 24]) 47 | axes.set_xticks(list(range(0, 24 + 1, 1))) 48 | 49 | matplotlib.pyplot.grid() 50 | 51 | fig = matplotlib.pyplot.gcf() 52 | fig.set_size_inches(11, 4) 53 | 54 | matplotlib.pyplot.legend([ls_box_phi1[0], ls_box_phi2[0]], ['$\\varphi_1$', '$\\varphi_2$']) 55 | 56 | matplotlib.pyplot.xlabel('Evaluation case') 57 | matplotlib.pyplot.ylabel('Number of traces') 58 | 59 | matplotlib.pyplot.savefig('./output/{}.png'.format(name), bbox_inches='tight') 60 | matplotlib.pyplot.close() 61 | 62 | 63 | def plot(line1, line2, line3, line4, name): 64 | matplotlib.pyplot.plot(line1, 'ro-', label='(a)') 65 | matplotlib.pyplot.plot(line2, 'go-', label='(b)') 66 | 67 | matplotlib.pyplot.plot(line3, 'bo-', label='(c)') 68 | matplotlib.pyplot.plot(line4, 'yo-', label='(d)') 69 | 70 | axes = matplotlib.pyplot.gca() 71 | axes.set_xlim([0, 24]) 72 | axes.set_xticks(list(range(0, 24 + 1, 1))) 73 | 74 | matplotlib.pyplot.grid() 75 | 76 | fig = matplotlib.pyplot.gcf() 77 | fig.set_size_inches(11, 4) 78 | 79 | matplotlib.pyplot.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, mode="expand", borderaxespad=0.) 80 | 81 | matplotlib.pyplot.xlabel('Evaluation case') 82 | matplotlib.pyplot.ylabel('Number of traces') 83 | 84 | matplotlib.pyplot.savefig('./output/{}.png'.format(name), bbox_inches='tight') 85 | matplotlib.pyplot.close() 86 | 87 | 88 | def diff(line1, line2): 89 | difference = line2 - line1 90 | mean = numpy.mean(difference) 91 | 92 | print('Difference: {}'.format(difference)) 93 | print('Mean: {}'.format(mean)) 94 | 95 | 96 | def get_avg(): 97 | print('Simulated') 98 | print('Avg (a): {}'.format(int(round(numpy.mean(sim_s_box_s_box))))) 99 | print('Min : {}'.format(numpy.amin(sim_s_box_s_box))) 100 | print('Max : {}'.format(numpy.amax(sim_s_box_s_box))) 101 | 102 | print('Avg (b): {}'.format(int(round(numpy.mean(sim_s_box_t_table))))) 103 | print('Min : {}'.format(numpy.amin(sim_s_box_t_table))) 104 | print('Max : {}'.format(numpy.amax(sim_s_box_t_table))) 105 | 106 | print('Avg (c): {}'.format(int(round(numpy.mean(sim_t_table_t_table))))) 107 | print('Min : {}'.format(numpy.amin(sim_t_table_t_table))) 108 | print('Max : {}'.format(numpy.amax(sim_t_table_t_table))) 109 | 110 | print('Avg (d): {}'.format(int(round(numpy.mean(sim_t_table_s_box))))) 111 | print('Min : {}'.format(numpy.amin(sim_t_table_s_box))) 112 | print('Max : {}'.format(numpy.amax(sim_t_table_s_box))) 113 | 114 | print() 115 | 116 | print('Real') 117 | print('Avg (a): {}'.format(int(round(numpy.mean(real_s_box_s_box))))) 118 | print('Min : {}'.format(numpy.amin(real_s_box_s_box))) 119 | print('Max : {}'.format(numpy.amax(real_s_box_s_box))) 120 | 121 | print('Avg (b): {}'.format(int(round(numpy.mean(real_s_box_t_table))))) 122 | print('Min : {}'.format(numpy.amin(real_s_box_t_table))) 123 | print('Max : {}'.format(numpy.amax(real_s_box_t_table))) 124 | 125 | print('Avg (c): {}'.format(int(round(numpy.mean(real_t_table_t_table))))) 126 | print('Min : {}'.format(numpy.amin(real_t_table_t_table))) 127 | print('Max : {}'.format(numpy.amax(real_t_table_t_table))) 128 | 129 | print('Avg (d): {}'.format(int(round(numpy.mean(real_t_table_s_box))))) 130 | print('Min : {}'.format(numpy.amin(real_t_table_s_box))) 131 | print('Max : {}'.format(numpy.amax(real_t_table_s_box))) 132 | 133 | print() 134 | 135 | 136 | def get_statistics(): 137 | print('Simulated S-box') 138 | diff(sim_s_box_s_box, sim_s_box_t_table) 139 | print() 140 | 141 | print('Simulated T-table') 142 | diff(sim_t_table_t_table, sim_t_table_s_box) 143 | print() 144 | 145 | print('Real S-box') 146 | diff(real_s_box_s_box, real_s_box_t_table) 147 | print() 148 | 149 | print('Real T-table') 150 | diff(real_t_table_t_table, real_t_table_s_box) 151 | print() 152 | 153 | 154 | def main(): 155 | get_avg() 156 | get_statistics() 157 | 158 | plot_short(sim_s_box_s_box, sim_s_box_t_table, 'simulated_s_box') 159 | plot_short(sim_t_table_s_box, sim_t_table_t_table, 'simulated_t_table') 160 | 161 | plot_short(real_s_box_s_box, real_s_box_t_table, 'real_s_box') 162 | plot_short(real_t_table_s_box, real_t_table_t_table, 'real_t_table') 163 | 164 | plot(sim_s_box_s_box, sim_s_box_t_table, sim_t_table_t_table, sim_t_table_s_box, 'simulated') 165 | plot(real_s_box_s_box, real_s_box_t_table, real_t_table_t_table, real_t_table_s_box, 'real') 166 | 167 | 168 | if "__main__" == __name__: 169 | main() 170 | -------------------------------------------------------------------------------- /correlation_coefficient_difference/delta_simulator.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import s_box, t0, t1, t2, t3 2 | from leakage_model.hw_s_box import HwSBox 3 | from leakage_model.hw_t_table import HwTTable 4 | 5 | 6 | import numpy 7 | import operator 8 | import random 9 | import scipy 10 | import scipy.stats 11 | import time 12 | 13 | 14 | class DeltaSimulator: 15 | def __init__(self): 16 | self.number_of_plaintexts = 2 ** 8 17 | self.subkey_size = 8 18 | 19 | self.number_of_samples = 1 20 | self.leaking_sample = self.number_of_samples // 2 21 | 22 | self.evaluation_case = None 23 | self.power_model = None 24 | self.traces = None 25 | 26 | self.init_type = 0 27 | if 0 == self.init_type: 28 | self.init_evaluation_case1() 29 | else: 30 | self.init_evaluation_case2() 31 | 32 | numpy.seterr(divide='ignore', invalid='ignore') 33 | 34 | def init_evaluation_case1(self, evaluation_case=-1): 35 | self.evaluation_case = evaluation_case 36 | 37 | if -1 == self.evaluation_case: 38 | self.power_model = HwSBox() 39 | max_hw = 8 40 | else: 41 | self.power_model = HwTTable() 42 | max_hw = 32 43 | 44 | self.traces = numpy.zeros((self.number_of_plaintexts, self.number_of_samples)) 45 | 46 | def init_evaluation_case2(self, evaluation_case=-1, targeted_key=0x00): 47 | self.evaluation_case = evaluation_case 48 | 49 | if -1 == self.evaluation_case: 50 | self.power_model = HwSBox() 51 | else: 52 | self.power_model = HwTTable() 53 | 54 | self.traces = numpy.zeros((self.number_of_plaintexts, self.number_of_samples)) 55 | 56 | random_keys = [0 for i in range(self.number_of_samples)] 57 | for i in range(self.number_of_samples): 58 | random_keys[i] = random.getrandbits(self.subkey_size) 59 | 60 | if i == self.leaking_sample and random_keys[i] == targeted_key: 61 | while random_keys[i] == targeted_key: 62 | random_keys[i] = random.getrandbits(self.subkey_size) 63 | 64 | if -1 == evaluation_case: 65 | for i in range(self.number_of_plaintexts): 66 | for j in range(self.number_of_samples): 67 | p = random.getrandbits(self.subkey_size) 68 | value = self.power_model.leak(s_box[p ^ random_keys[j]]) 69 | self.traces[i][j] = value 70 | elif 0 == evaluation_case: 71 | for i in range(self.number_of_plaintexts): 72 | for j in range(self.number_of_samples): 73 | p = random.getrandbits(self.subkey_size) 74 | value = self.power_model.leak(t0[p ^ random_keys[j]]) 75 | self.traces[i][j] = value 76 | elif 1 == evaluation_case: 77 | for i in range(self.number_of_plaintexts): 78 | for j in range(self.number_of_samples): 79 | p = random.getrandbits(self.subkey_size) 80 | value = self.power_model.leak(t1[p ^ random_keys[j]]) 81 | self.traces[i][j] = value 82 | elif 2 == evaluation_case: 83 | for i in range(self.number_of_plaintexts): 84 | for j in range(self.number_of_samples): 85 | p = random.getrandbits(self.subkey_size) 86 | value = self.power_model.leak(t2[p ^ random_keys[j]]) 87 | self.traces[i][j] = value 88 | elif 3 == evaluation_case: 89 | for i in range(self.number_of_plaintexts): 90 | for j in range(self.number_of_samples): 91 | p = random.getrandbits(self.subkey_size) 92 | value = self.power_model.leak(t3[p ^ random_keys[j]]) 93 | self.traces[i][j] = value 94 | 95 | def generate_leakage(self, k): 96 | for p in range(self.number_of_plaintexts): 97 | c = s_box[p ^ k] 98 | self.traces[p][self.leaking_sample] = self.power_model.leak(c) 99 | 100 | @staticmethod 101 | def pcc(p, o): 102 | n = p.size 103 | do = o - (numpy.einsum('ij->j', o) / numpy.double(n)) 104 | p -= (numpy.einsum('i->', p) / numpy.double(n)) 105 | tmp = numpy.einsum('ij,ij->j', do, do) 106 | tmp *= numpy.einsum('i,i->', p, p) 107 | return numpy.dot(p, do) / numpy.sqrt(tmp) 108 | 109 | def predict_power_consumption(self, plaintext, key): 110 | value = plaintext ^ key 111 | 112 | if -1 == self.evaluation_case: 113 | value = s_box[value] 114 | elif 0 == self.evaluation_case: 115 | value = t0[value] 116 | elif 1 == self.evaluation_case: 117 | value = t1[value] 118 | elif 2 == self.evaluation_case: 119 | value = t2[value] 120 | elif 3 == self.evaluation_case: 121 | value = t3[value] 122 | 123 | return self.power_model.leak(value) 124 | 125 | def get_delta(self, correlation_matrix, expected_key): 126 | correlation_coefficients = [0] * (2 ** self.subkey_size) 127 | 128 | for i in range(correlation_matrix.shape[0]): 129 | max_value_index = numpy.argmax(correlation_matrix[i]) 130 | max_value = correlation_matrix[i][max_value_index] 131 | correlation_coefficients[i] = (i, max_value, max_value_index) 132 | 133 | correlation_coefficients = sorted(correlation_coefficients, key=operator.itemgetter(1), reverse=True) 134 | 135 | delta_1 = 0 136 | delta_2 = 0 137 | 138 | rank_index = -1 139 | break_next = False 140 | for i in range(len(correlation_coefficients)): 141 | key = correlation_coefficients[i][0] 142 | value = correlation_coefficients[i][1] 143 | sample = correlation_coefficients[i][2] 144 | 145 | rank_index += 1 146 | 147 | # print('Rank {}: 0x{} {:1.010} ({})'.format(rank_index, format(key, '02x'), value, sample)) 148 | 149 | if break_next: 150 | break 151 | 152 | if expected_key == key: 153 | delta_1 = value 154 | 155 | if 0 != i: 156 | delta_2 = correlation_coefficients[0][1] 157 | else: 158 | delta_2 = correlation_coefficients[i + 1][1] 159 | break_next = True 160 | 161 | delta = delta_1 - delta_2 162 | # print('d1 (expected) : {:+1.06}'.format(delta_1)) 163 | # print('d2 (best != expected) : {:+1.06}'.format(delta_2)) 164 | # print('d (d1 - d2) : {:+1.06}'.format(delta)) 165 | 166 | return delta 167 | 168 | def attack(self, expected_key): 169 | hypothetical_power_consumption = numpy.zeros((self.number_of_plaintexts, 2 ** self.subkey_size)) 170 | 171 | for p in range(self.number_of_plaintexts): 172 | for k in range(2 ** self.subkey_size): 173 | power = self.predict_power_consumption(p, k) 174 | hypothetical_power_consumption[p][k] = power 175 | 176 | correlation_matrix = numpy.zeros((2 ** self.subkey_size, self.number_of_samples)) 177 | 178 | for i in range(2 ** self.subkey_size): 179 | pcc = self.pcc(hypothetical_power_consumption[:, i], self.traces) 180 | correlation_matrix[i] = pcc 181 | 182 | correlation_matrix = numpy.nan_to_num(correlation_matrix) 183 | delta = self.get_delta(correlation_matrix, expected_key) 184 | 185 | return delta 186 | 187 | def check_all(self, evaluation_case=-1): 188 | if 0 == self.init_type: 189 | self.init_evaluation_case1(evaluation_case) 190 | else: 191 | self.init_evaluation_case2() 192 | 193 | delta_value = 0 194 | 195 | for k in range(2 ** self.subkey_size): 196 | if 0 != self.init_type: 197 | self.init_evaluation_case2(evaluation_case, k) 198 | 199 | self.generate_leakage(k) 200 | delta = self.attack(k) 201 | 202 | if 0 == k: 203 | delta_value = delta 204 | 205 | if delta_value != delta: 206 | print('Error: key 0x{} has delta {:+1.06}, not {:+1.06}!'.format(format(k, '02x'), delta, delta_value)) 207 | 208 | return delta_value 209 | 210 | def run(self, key, evaluation_case=-1): 211 | if 0 == self.init_type: 212 | self.init_evaluation_case1(evaluation_case) 213 | else: 214 | self.init_evaluation_case2(evaluation_case, key) 215 | 216 | self.generate_leakage(key) 217 | delta = self.attack(key) 218 | 219 | return delta 220 | 221 | 222 | def run_keys(evaluation_case=-1, key1=0x00, key2=0x0F, key3=0xFF): 223 | delta_s = DeltaSimulator() 224 | 225 | delta = delta_s.run(key1, evaluation_case) 226 | print('k = 0x{}: {:+1.03}'.format(format(key1, '02x'), delta)) 227 | 228 | delta = delta_s.run(key2, evaluation_case) 229 | print('k = 0x{}: {:+1.03}'.format(format(key2, '02x'), delta)) 230 | 231 | delta = delta_s.run(key3, evaluation_case) 232 | print('k = 0x{}: {:+1.03}'.format(format(key3, '02x'), delta)) 233 | 234 | 235 | def run(): 236 | number_of_experiments = 10 237 | 238 | evaluation_cases = [-1, 0, 1, 2, 3] 239 | 240 | keys = list(range(2 ** 8)) 241 | 242 | delta_s = DeltaSimulator() 243 | for evaluation_case in evaluation_cases: 244 | 245 | print('Evaluation case: {:+1}'.format(evaluation_case)) 246 | 247 | global_delta = [0 for i in range(len(keys))] 248 | global_index = 0 249 | 250 | for k in keys: 251 | delta = [0 for i in range(number_of_experiments)] 252 | 253 | for experiment in range(number_of_experiments): 254 | delta[experiment] = delta_s.run(k, evaluation_case) 255 | 256 | global_delta[global_index] = numpy.mean(delta) 257 | global_index += 1 258 | 259 | global_delta = 1.0 * numpy.array(global_delta) 260 | n = len(global_delta) 261 | 262 | confidence = 0.95 263 | m, se = numpy.mean(global_delta), scipy.stats.sem(global_delta) 264 | h = se * scipy.stats.t._ppf((1 + confidence) / 2., n - 1) 265 | 266 | print('global delta = {}'.format(global_delta)) 267 | 268 | print('Result: {:+1.03} {:+1.03}'.format(m, h)) 269 | print() 270 | 271 | 272 | def check_all(): 273 | delta_simulator = DeltaSimulator() 274 | delta_simulator.check_all() 275 | 276 | 277 | if "__main__" == __name__: 278 | start_time = time.time() 279 | 280 | # run_keys() 281 | run() 282 | # check_all() 283 | 284 | stop_time = time.time() 285 | 286 | print() 287 | print('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(stop_time - start_time)))) 288 | -------------------------------------------------------------------------------- /symbolic_evaluator/evaluation_case_solver.py: -------------------------------------------------------------------------------- 1 | class EvaluationCaseSolver: 2 | def __init__(self, initial_state): 3 | self.state = [[0 for i in range(16)] for j in range(4)] 4 | self.pairs = [[[] for i in range(16)] for j in range(4)] 5 | 6 | self.pair_number = 0 7 | 8 | for i in range(16): 9 | self.state[0][i] = initial_state[i] 10 | 11 | def recovered(self, round_number): 12 | for i in range(16): 13 | if 0 >= self.state[round_number][i]: 14 | return False 15 | 16 | return True 17 | 18 | def variable_inputs(self, round_number, in_index0, in_index1, in_index2, in_index3): 19 | variable_inputs = 0 20 | 21 | if 0 != self.state[round_number - 1][in_index0]: 22 | variable_inputs += 1 23 | if 0 != self.state[round_number - 1][in_index1]: 24 | variable_inputs += 1 25 | if 0 != self.state[round_number - 1][in_index2]: 26 | variable_inputs += 1 27 | if 0 != self.state[round_number - 1][in_index3]: 28 | variable_inputs += 1 29 | 30 | return variable_inputs 31 | 32 | def independent_candidates(self, round_number, in_index0, in_index1, in_index2, in_index3): 33 | candidates = 1 34 | 35 | previous_pairs = self.combine_pairs(self.pairs[round_number - 1][in_index0], 36 | self.pairs[round_number - 1][in_index1], 37 | self.pairs[round_number - 1][in_index2], 38 | self.pairs[round_number - 1][in_index3]) 39 | 40 | if 0 < len(previous_pairs): 41 | candidates = 2 ** len(previous_pairs) 42 | 43 | return candidates 44 | 45 | @staticmethod 46 | def combine_pairs(pair0, pair1, pair2='', pair3=''): 47 | pair0 = set(pair0) 48 | pair1 = set(pair1) 49 | pair2 = set(pair2) 50 | pair3 = set(pair3) 51 | 52 | new_pair = pair0.union(pair1) 53 | new_pair = new_pair.union(pair2) 54 | new_pair = new_pair.union(pair3) 55 | new_pair = list(new_pair) 56 | 57 | return new_pair 58 | 59 | def update(self, round_number, in_index0, in_index1, in_index2, in_index3, 60 | out_index0, out_index1, out_index2, out_index3): 61 | variable_inputs = self.variable_inputs(round_number, in_index0, in_index1, in_index2, in_index3) 62 | candidates = self.independent_candidates(round_number, in_index0, in_index1, in_index2, in_index3) 63 | 64 | previous_pairs = self.combine_pairs(self.pairs[round_number - 1][in_index0], 65 | self.pairs[round_number - 1][in_index1], 66 | self.pairs[round_number - 1][in_index2], 67 | self.pairs[round_number - 1][in_index3]) 68 | 69 | self.pairs[round_number][out_index0] = previous_pairs 70 | self.pairs[round_number][out_index1] = previous_pairs 71 | self.pairs[round_number][out_index2] = previous_pairs 72 | self.pairs[round_number][out_index3] = previous_pairs 73 | 74 | if 0 == variable_inputs: 75 | self.state[round_number][out_index0] = 0 76 | self.state[round_number][out_index1] = 0 77 | self.state[round_number][out_index2] = 0 78 | self.state[round_number][out_index3] = 0 79 | elif 1 == variable_inputs: 80 | if 0 != self.state[round_number - 1][in_index0]: 81 | self.state[round_number][out_index0] = -1 * candidates 82 | self.state[round_number][out_index1] = -2 * candidates 83 | self.state[round_number][out_index2] = -2 * candidates 84 | self.state[round_number][out_index3] = -1 * candidates 85 | 86 | self.pair_number += 1 87 | self.pairs[round_number][out_index1] = self.combine_pairs(self.pairs[round_number][out_index1], 88 | [self.pair_number]) 89 | self.pairs[round_number][out_index2] = self.combine_pairs(self.pairs[round_number][out_index2], 90 | [self.pair_number]) 91 | if 0 != self.state[round_number - 1][in_index1]: 92 | self.state[round_number][out_index0] = -1 * candidates 93 | self.state[round_number][out_index1] = -1 * candidates 94 | self.state[round_number][out_index2] = -2 * candidates 95 | self.state[round_number][out_index3] = -2 * candidates 96 | 97 | self.pair_number += 1 98 | self.pairs[round_number][out_index2] = self.combine_pairs(self.pairs[round_number][out_index2], 99 | [self.pair_number]) 100 | self.pairs[round_number][out_index3] = self.combine_pairs(self.pairs[round_number][out_index3], 101 | [self.pair_number]) 102 | if 0 != self.state[round_number - 1][in_index2]: 103 | self.state[round_number][out_index0] = -2 * candidates 104 | self.state[round_number][out_index1] = -1 * candidates 105 | self.state[round_number][out_index2] = -1 * candidates 106 | self.state[round_number][out_index3] = -2 * candidates 107 | 108 | self.pair_number += 1 109 | self.pairs[round_number][out_index0] = self.combine_pairs(self.pairs[round_number][out_index0], 110 | [self.pair_number]) 111 | self.pairs[round_number][out_index3] = self.combine_pairs(self.pairs[round_number][out_index3], 112 | [self.pair_number]) 113 | if 0 != self.state[round_number - 1][in_index3]: 114 | self.state[round_number][out_index0] = -2 * candidates 115 | self.state[round_number][out_index1] = -2 * candidates 116 | self.state[round_number][out_index2] = -1 * candidates 117 | self.state[round_number][out_index3] = -1 * candidates 118 | 119 | self.pair_number += 1 120 | self.pairs[round_number][out_index0] = self.combine_pairs(self.pairs[round_number][out_index0], 121 | [self.pair_number]) 122 | self.pairs[round_number][out_index1] = self.combine_pairs(self.pairs[round_number][out_index1], 123 | [self.pair_number]) 124 | elif variable_inputs in [2, 3]: 125 | self.state[round_number][out_index0] = -1 126 | self.state[round_number][out_index1] = -1 127 | self.state[round_number][out_index2] = -1 128 | self.state[round_number][out_index3] = -1 129 | elif 4 == variable_inputs: 130 | self.state[round_number][out_index0] = 1 131 | self.state[round_number][out_index1] = 1 132 | self.state[round_number][out_index2] = 1 133 | self.state[round_number][out_index3] = 1 134 | 135 | def attack(self, round_number): 136 | if 0 == round_number: 137 | return 138 | 139 | self.update(round_number, 0, 5, 10, 15, 0, 1, 2, 3) 140 | self.update(round_number, 4, 9, 14, 3, 4, 5, 6, 7) 141 | self.update(round_number, 8, 13, 2, 7, 8, 9, 10, 11) 142 | self.update(round_number, 12, 1, 6, 11, 12, 13, 14, 15) 143 | 144 | def process(self): 145 | round_number = 0 146 | 147 | while True: 148 | self.attack(round_number) 149 | 150 | if self.recovered(round_number): 151 | break 152 | round_number += 1 153 | 154 | def get_possible_keys(self, i): 155 | return self.state[i][0] 156 | 157 | def get_statistics(self): 158 | possible_keys = -1 159 | number_of_rounds = -1 160 | 161 | for i in range(3, -1, -1): 162 | if self.recovered(i): 163 | possible_keys = self.get_possible_keys(i) 164 | number_of_rounds = i + 1 165 | break 166 | 167 | return possible_keys, number_of_rounds 168 | 169 | def max_possible_keys(self, pairs): 170 | pair1 = self.combine_pairs(pairs[0], pairs[1], pairs[2], pairs[3]) 171 | pair2 = self.combine_pairs(pairs[4], pairs[5], pairs[6], pairs[7]) 172 | pair3 = self.combine_pairs(pairs[8], pairs[9], pairs[10], pairs[11]) 173 | pair4 = self.combine_pairs(pairs[12], pairs[13], pairs[14], pairs[15]) 174 | independent_pairs = self.combine_pairs(pair1, pair2, pair3, pair4) 175 | 176 | return 2 ** len(independent_pairs) 177 | 178 | def get_max_possible_keys(self): 179 | for i in range(3, -1, -1): 180 | if self.recovered(i): 181 | return self.max_possible_keys(self.pairs[i]) 182 | 183 | return -1 184 | 185 | def print_state(self, round_number=-1): 186 | if -1 == round_number: 187 | for i in range(4): 188 | self.print_state(i) 189 | return 190 | 191 | print('round {}: state'.format(round_number), end='') 192 | for i in range(4): 193 | print('\n\t', end='') 194 | for j in range(4): 195 | print('{:2} '.format(self.state[round_number][i + 4 * j]), end='') 196 | print() 197 | 198 | def print_pairs(self, round_number=-1): 199 | if -1 == round_number: 200 | for i in range(4): 201 | self.print_pairs(i) 202 | return 203 | 204 | print('round {}: pairs'.format(round_number), end='') 205 | for i in range(4): 206 | print('\n\t', end='') 207 | for j in range(4): 208 | print('{} '.format(self.pairs[round_number][i + 4 * j]), end='') 209 | print() 210 | 211 | def print_state_pairs(self, round_number=-1): 212 | if -1 == round_number: 213 | for i in range(4): 214 | self.print_state_pairs(i) 215 | return 216 | 217 | print('round {}: state \t\t\t pairs'.format(round_number), end='') 218 | for i in range(4): 219 | print('\n\t', end='') 220 | for j in range(4): 221 | print('{:2} '.format(self.state[round_number][i + 4 * j]), end='') 222 | print('\t ', end='') 223 | for j in range(4): 224 | print('{} '.format(self.pairs[round_number][i + 4 * j]), end='') 225 | print() 226 | 227 | def get_pair_indexes(self, pair, round_number): 228 | indexes = [] 229 | 230 | for i in range(16): 231 | if pair in set(self.pairs[round_number][i]): 232 | indexes.append(16 * round_number + i) 233 | 234 | return indexes 235 | 236 | 237 | def main(): 238 | initial_state = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 239 | 240 | evaluation_case = EvaluationCaseSolver(initial_state) 241 | evaluation_case.process() 242 | 243 | # evaluation_case.print_state() 244 | # evaluation_case.print_pairs() 245 | evaluation_case.print_state_pairs() 246 | 247 | print() 248 | print('(keys, rounds) = {}'.format(evaluation_case.get_statistics())) 249 | 250 | 251 | if "__main__" == __name__: 252 | main() 253 | -------------------------------------------------------------------------------- /cpa_attacker/round1.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import s_box 2 | 3 | 4 | import copy 5 | 6 | 7 | class Round1: 8 | def __init__(self, round_keys, state): 9 | self.round_keys = round_keys 10 | self.state = copy.deepcopy(state) 11 | 12 | for i in range(len(state)): 13 | for j in range(16): 14 | if 0 != self.state[i][j]: 15 | self.state[i][j] = 1 16 | 17 | @staticmethod 18 | def multiply(a, b): 19 | p = 0 20 | 21 | for i in range(8): 22 | if 1 == b & 1: 23 | p ^= a 24 | high_bit_set = a & 0x80 25 | a = (a << 1) & 0xff 26 | if 0x80 == high_bit_set: 27 | a ^= 0x1b 28 | b >>= 1 29 | 30 | return p 31 | 32 | def get_plaintext_part(self, plaintext, index): 33 | if 16 == index: 34 | return self.get_plaintext_part_round1_k0(plaintext) 35 | elif 17 == index: 36 | return self.get_plaintext_part_round1_k1(plaintext) 37 | elif 18 == index: 38 | return self.get_plaintext_part_round1_k2(plaintext) 39 | elif 19 == index: 40 | return self.get_plaintext_part_round1_k3(plaintext) 41 | elif 20 == index: 42 | return self.get_plaintext_part_round1_k4(plaintext) 43 | elif 21 == index: 44 | return self.get_plaintext_part_round1_k5(plaintext) 45 | elif 22 == index: 46 | return self.get_plaintext_part_round1_k6(plaintext) 47 | elif 23 == index: 48 | return self.get_plaintext_part_round1_k7(plaintext) 49 | elif 24 == index: 50 | return self.get_plaintext_part_round1_k8(plaintext) 51 | elif 25 == index: 52 | return self.get_plaintext_part_round1_k9(plaintext) 53 | elif 26 == index: 54 | return self.get_plaintext_part_round1_k10(plaintext) 55 | elif 27 == index: 56 | return self.get_plaintext_part_round1_k11(plaintext) 57 | elif 28 == index: 58 | return self.get_plaintext_part_round1_k12(plaintext) 59 | elif 29 == index: 60 | return self.get_plaintext_part_round1_k13(plaintext) 61 | elif 30 == index: 62 | return self.get_plaintext_part_round1_k14(plaintext) 63 | elif 31 == index: 64 | return self.get_plaintext_part_round1_k15(plaintext) 65 | 66 | def get_plaintext_part_round1_k0(self, plaintext): 67 | # Round 0 68 | x0 = (plaintext >> 120) & 0xff 69 | x5 = (plaintext >> 80) & 0xff 70 | x10 = (plaintext >> 40) & 0xff 71 | x15 = (plaintext >> 0) & 0xff 72 | 73 | # AddRoundKey 74 | x0 ^= self.round_keys[0] 75 | x5 ^= self.round_keys[5] 76 | x10 ^= self.round_keys[10] 77 | x15 ^= self.round_keys[15] 78 | 79 | # SubBytes 80 | y0 = s_box[x0] 81 | y5 = s_box[x5] 82 | y10 = s_box[x10] 83 | y15 = s_box[x15] 84 | 85 | y0 *= self.state[0][0] 86 | y5 *= self.state[0][5] 87 | y10 *= self.state[0][10] 88 | y15 *= self.state[0][15] 89 | 90 | z = self.multiply(y0, 2) ^ self.multiply(y5, 3) ^ y10 ^ y15 91 | return z 92 | 93 | def get_plaintext_part_round1_k1(self, plaintext): 94 | # Round 0 95 | x0 = (plaintext >> 120) & 0xff 96 | x5 = (plaintext >> 80) & 0xff 97 | x10 = (plaintext >> 40) & 0xff 98 | x15 = (plaintext >> 0) & 0xff 99 | 100 | # AddRoundKey 101 | x0 ^= self.round_keys[0] 102 | x5 ^= self.round_keys[5] 103 | x10 ^= self.round_keys[10] 104 | x15 ^= self.round_keys[15] 105 | 106 | # SubBytes 107 | y0 = s_box[x0] 108 | y5 = s_box[x5] 109 | y10 = s_box[x10] 110 | y15 = s_box[x15] 111 | 112 | y0 *= self.state[0][0] 113 | y5 *= self.state[0][5] 114 | y10 *= self.state[0][10] 115 | y15 *= self.state[0][15] 116 | 117 | z = y0 ^ self.multiply(y5, 2) ^ self.multiply(y10, 3) ^ y15 118 | return z 119 | 120 | def get_plaintext_part_round1_k2(self, plaintext): 121 | # Round 0 122 | x0 = (plaintext >> 120) & 0xff 123 | x5 = (plaintext >> 80) & 0xff 124 | x10 = (plaintext >> 40) & 0xff 125 | x15 = (plaintext >> 0) & 0xff 126 | 127 | # AddRoundKey 128 | x0 ^= self.round_keys[0] 129 | x5 ^= self.round_keys[5] 130 | x10 ^= self.round_keys[10] 131 | x15 ^= self.round_keys[15] 132 | 133 | # SubBytes 134 | y0 = s_box[x0] 135 | y5 = s_box[x5] 136 | y10 = s_box[x10] 137 | y15 = s_box[x15] 138 | 139 | y0 *= self.state[0][0] 140 | y5 *= self.state[0][5] 141 | y10 *= self.state[0][10] 142 | y15 *= self.state[0][15] 143 | 144 | z = y0 ^ y5 ^ self.multiply(y10, 2) ^ self.multiply(y15, 3) 145 | return z 146 | 147 | def get_plaintext_part_round1_k3(self, plaintext): 148 | # Round 0 149 | x0 = (plaintext >> 120) & 0xff 150 | x5 = (plaintext >> 80) & 0xff 151 | x10 = (plaintext >> 40) & 0xff 152 | x15 = (plaintext >> 0) & 0xff 153 | 154 | # AddRoundKey 155 | x0 ^= self.round_keys[0] 156 | x5 ^= self.round_keys[5] 157 | x10 ^= self.round_keys[10] 158 | x15 ^= self.round_keys[15] 159 | 160 | # SubBytes 161 | y0 = s_box[x0] 162 | y5 = s_box[x5] 163 | y10 = s_box[x10] 164 | y15 = s_box[x15] 165 | 166 | y0 *= self.state[0][0] 167 | y5 *= self.state[0][5] 168 | y10 *= self.state[0][10] 169 | y15 *= self.state[0][15] 170 | 171 | z = self.multiply(y0, 3) ^ y5 ^ y10 ^ self.multiply(y15, 2) 172 | return z 173 | 174 | def get_plaintext_part_round1_k4(self, plaintext): 175 | # Round 0 176 | x4 = (plaintext >> 88) & 0xff 177 | x9 = (plaintext >> 48) & 0xff 178 | x14 = (plaintext >> 8) & 0xff 179 | x3 = (plaintext >> 96) & 0xff 180 | 181 | # AddRoundKey 182 | x4 ^= self.round_keys[4] 183 | x9 ^= self.round_keys[9] 184 | x14 ^= self.round_keys[14] 185 | x3 ^= self.round_keys[3] 186 | 187 | # SubBytes 188 | y4 = s_box[x4] 189 | y9 = s_box[x9] 190 | y14 = s_box[x14] 191 | y3 = s_box[x3] 192 | 193 | y4 *= self.state[0][4] 194 | y9 *= self.state[0][9] 195 | y14 *= self.state[0][14] 196 | y3 *= self.state[0][3] 197 | 198 | z = self.multiply(y4, 2) ^ self.multiply(y9, 3) ^ y14 ^ y3 199 | return z 200 | 201 | def get_plaintext_part_round1_k5(self, plaintext): 202 | # Round 0 203 | x4 = (plaintext >> 88) & 0xff 204 | x9 = (plaintext >> 48) & 0xff 205 | x14 = (plaintext >> 8) & 0xff 206 | x3 = (plaintext >> 96) & 0xff 207 | 208 | # AddRoundKey 209 | x4 ^= self.round_keys[4] 210 | x9 ^= self.round_keys[9] 211 | x14 ^= self.round_keys[14] 212 | x3 ^= self.round_keys[3] 213 | 214 | # SubBytes 215 | y4 = s_box[x4] 216 | y9 = s_box[x9] 217 | y14 = s_box[x14] 218 | y3 = s_box[x3] 219 | 220 | y4 *= self.state[0][4] 221 | y9 *= self.state[0][9] 222 | y14 *= self.state[0][14] 223 | y3 *= self.state[0][3] 224 | 225 | z = y4 ^ self.multiply(y9, 2) ^ self.multiply(y14, 3) ^ y3 226 | return z 227 | 228 | def get_plaintext_part_round1_k6(self, plaintext): 229 | # Round 0 230 | x4 = (plaintext >> 88) & 0xff 231 | x9 = (plaintext >> 48) & 0xff 232 | x14 = (plaintext >> 8) & 0xff 233 | x3 = (plaintext >> 96) & 0xff 234 | 235 | # AddRoundKey 236 | x4 ^= self.round_keys[4] 237 | x9 ^= self.round_keys[9] 238 | x14 ^= self.round_keys[14] 239 | x3 ^= self.round_keys[3] 240 | 241 | # SubBytes 242 | y4 = s_box[x4] 243 | y9 = s_box[x9] 244 | y14 = s_box[x14] 245 | y3 = s_box[x3] 246 | 247 | y4 *= self.state[0][4] 248 | y9 *= self.state[0][9] 249 | y14 *= self.state[0][14] 250 | y3 *= self.state[0][3] 251 | 252 | z = y4 ^ y9 ^ self.multiply(y14, 2) ^ self.multiply(y3, 3) 253 | return z 254 | 255 | def get_plaintext_part_round1_k7(self, plaintext): 256 | # Round 0 257 | x4 = (plaintext >> 88) & 0xff 258 | x9 = (plaintext >> 48) & 0xff 259 | x14 = (plaintext >> 8) & 0xff 260 | x3 = (plaintext >> 96) & 0xff 261 | 262 | # AddRoundKey 263 | x4 ^= self.round_keys[4] 264 | x9 ^= self.round_keys[9] 265 | x14 ^= self.round_keys[14] 266 | x3 ^= self.round_keys[3] 267 | 268 | # SubBytes 269 | y4 = s_box[x4] 270 | y9 = s_box[x9] 271 | y14 = s_box[x14] 272 | y3 = s_box[x3] 273 | 274 | y4 *= self.state[0][4] 275 | y9 *= self.state[0][9] 276 | y14 *= self.state[0][14] 277 | y3 *= self.state[0][3] 278 | 279 | z = self.multiply(y4, 3) ^ y9 ^ y14 ^ self.multiply(y3, 2) 280 | return z 281 | 282 | def get_plaintext_part_round1_k8(self, plaintext): 283 | # Round 0 284 | x8 = (plaintext >> 56) & 0xff 285 | x13 = (plaintext >> 16) & 0xff 286 | x2 = (plaintext >> 104) & 0xff 287 | x7 = (plaintext >> 64) & 0xff 288 | 289 | # AddRoundKey 290 | x8 ^= self.round_keys[8] 291 | x13 ^= self.round_keys[13] 292 | x2 ^= self.round_keys[2] 293 | x7 ^= self.round_keys[7] 294 | 295 | # SubBytes 296 | y8 = s_box[x8] 297 | y13 = s_box[x13] 298 | y2 = s_box[x2] 299 | y7 = s_box[x7] 300 | 301 | y8 *= self.state[0][8] 302 | y13 *= self.state[0][13] 303 | y2 *= self.state[0][2] 304 | y7 *= self.state[0][7] 305 | 306 | z = self.multiply(y8, 2) ^ self.multiply(y13, 3) ^ y2 ^ y7 307 | return z 308 | 309 | def get_plaintext_part_round1_k9(self, plaintext): 310 | # Round 0 311 | x8 = (plaintext >> 56) & 0xff 312 | x13 = (plaintext >> 16) & 0xff 313 | x2 = (plaintext >> 104) & 0xff 314 | x7 = (plaintext >> 64) & 0xff 315 | 316 | # AddRoundKey 317 | x8 ^= self.round_keys[8] 318 | x13 ^= self.round_keys[13] 319 | x2 ^= self.round_keys[2] 320 | x7 ^= self.round_keys[7] 321 | 322 | # SubBytes 323 | y8 = s_box[x8] 324 | y13 = s_box[x13] 325 | y2 = s_box[x2] 326 | y7 = s_box[x7] 327 | 328 | y8 *= self.state[0][8] 329 | y13 *= self.state[0][13] 330 | y2 *= self.state[0][2] 331 | y7 *= self.state[0][7] 332 | 333 | z = y8 ^ self.multiply(y13, 2) ^ self.multiply(y2, 3) ^ y7 334 | return z 335 | 336 | def get_plaintext_part_round1_k10(self, plaintext): 337 | # Round 0 338 | x8 = (plaintext >> 56) & 0xff 339 | x13 = (plaintext >> 16) & 0xff 340 | x2 = (plaintext >> 104) & 0xff 341 | x7 = (plaintext >> 64) & 0xff 342 | 343 | # AddRoundKey 344 | x8 ^= self.round_keys[8] 345 | x13 ^= self.round_keys[13] 346 | x2 ^= self.round_keys[2] 347 | x7 ^= self.round_keys[7] 348 | 349 | # SubBytes 350 | y8 = s_box[x8] 351 | y13 = s_box[x13] 352 | y2 = s_box[x2] 353 | y7 = s_box[x7] 354 | 355 | y8 *= self.state[0][8] 356 | y13 *= self.state[0][13] 357 | y2 *= self.state[0][2] 358 | y7 *= self.state[0][7] 359 | 360 | z = y8 ^ y13 ^ self.multiply(y2, 2) ^ self.multiply(y7, 3) 361 | return z 362 | 363 | def get_plaintext_part_round1_k11(self, plaintext): 364 | # Round 0 365 | x8 = (plaintext >> 56) & 0xff 366 | x13 = (plaintext >> 16) & 0xff 367 | x2 = (plaintext >> 104) & 0xff 368 | x7 = (plaintext >> 64) & 0xff 369 | 370 | # AddRoundKey 371 | x8 ^= self.round_keys[8] 372 | x13 ^= self.round_keys[13] 373 | x2 ^= self.round_keys[2] 374 | x7 ^= self.round_keys[7] 375 | 376 | # SubBytes 377 | y8 = s_box[x8] 378 | y13 = s_box[x13] 379 | y2 = s_box[x2] 380 | y7 = s_box[x7] 381 | 382 | y8 *= self.state[0][8] 383 | y13 *= self.state[0][13] 384 | y2 *= self.state[0][2] 385 | y7 *= self.state[0][7] 386 | 387 | z = self.multiply(y8, 3) ^ y13 ^ y2 ^ self.multiply(y7, 2) 388 | return z 389 | 390 | def get_plaintext_part_round1_k12(self, plaintext): 391 | # Round 0 392 | x12 = (plaintext >> 24) & 0xff 393 | x1 = (plaintext >> 112) & 0xff 394 | x6 = (plaintext >> 72) & 0xff 395 | x11 = (plaintext >> 32) & 0xff 396 | 397 | # AddRoundKey 398 | x12 ^= self.round_keys[12] 399 | x1 ^= self.round_keys[1] 400 | x6 ^= self.round_keys[6] 401 | x11 ^= self.round_keys[11] 402 | 403 | # SubBytes 404 | y12 = s_box[x12] 405 | y1 = s_box[x1] 406 | y6 = s_box[x6] 407 | y11 = s_box[x11] 408 | 409 | y12 *= self.state[0][12] 410 | y1 *= self.state[0][1] 411 | y6 *= self.state[0][6] 412 | y11 *= self.state[0][11] 413 | 414 | z = self.multiply(y12, 2) ^ self.multiply(y1, 3) ^ y6 ^ y11 415 | return z 416 | 417 | def get_plaintext_part_round1_k13(self, plaintext): 418 | # Round 0 419 | x12 = (plaintext >> 24) & 0xff 420 | x1 = (plaintext >> 112) & 0xff 421 | x6 = (plaintext >> 72) & 0xff 422 | x11 = (plaintext >> 32) & 0xff 423 | 424 | # AddRoundKey 425 | x12 ^= self.round_keys[12] 426 | x1 ^= self.round_keys[1] 427 | x6 ^= self.round_keys[6] 428 | x11 ^= self.round_keys[11] 429 | 430 | # SubBytes 431 | y12 = s_box[x12] 432 | y1 = s_box[x1] 433 | y6 = s_box[x6] 434 | y11 = s_box[x11] 435 | 436 | y12 *= self.state[0][12] 437 | y1 *= self.state[0][1] 438 | y6 *= self.state[0][6] 439 | y11 *= self.state[0][11] 440 | 441 | z = y12 ^ self.multiply(y1, 2) ^ self.multiply(y6, 3) ^ y11 442 | return z 443 | 444 | def get_plaintext_part_round1_k14(self, plaintext): 445 | # Round 0 446 | x12 = (plaintext >> 24) & 0xff 447 | x1 = (plaintext >> 112) & 0xff 448 | x6 = (plaintext >> 72) & 0xff 449 | x11 = (plaintext >> 32) & 0xff 450 | 451 | # AddRoundKey 452 | x12 ^= self.round_keys[12] 453 | x1 ^= self.round_keys[1] 454 | x6 ^= self.round_keys[6] 455 | x11 ^= self.round_keys[11] 456 | 457 | # SubBytes 458 | y12 = s_box[x12] 459 | y1 = s_box[x1] 460 | y6 = s_box[x6] 461 | y11 = s_box[x11] 462 | 463 | y12 *= self.state[0][12] 464 | y1 *= self.state[0][1] 465 | y6 *= self.state[0][6] 466 | y11 *= self.state[0][11] 467 | 468 | z = y12 ^ y1 ^ self.multiply(y6, 2) ^ self.multiply(y11, 3) 469 | return z 470 | 471 | def get_plaintext_part_round1_k15(self, plaintext): 472 | # Round 0 473 | x12 = (plaintext >> 24) & 0xff 474 | x1 = (plaintext >> 112) & 0xff 475 | x6 = (plaintext >> 72) & 0xff 476 | x11 = (plaintext >> 32) & 0xff 477 | 478 | # AddRoundKey 479 | x12 ^= self.round_keys[12] 480 | x1 ^= self.round_keys[1] 481 | x6 ^= self.round_keys[6] 482 | x11 ^= self.round_keys[11] 483 | 484 | # SubBytes 485 | y12 = s_box[x12] 486 | y1 = s_box[x1] 487 | y6 = s_box[x6] 488 | y11 = s_box[x11] 489 | 490 | y12 *= self.state[0][12] 491 | y1 *= self.state[0][1] 492 | y6 *= self.state[0][6] 493 | y11 *= self.state[0][11] 494 | 495 | z = self.multiply(y12, 3) ^ y1 ^ y6 ^ self.multiply(y11, 2) 496 | return z 497 | -------------------------------------------------------------------------------- /aes_cipher/constants.py: -------------------------------------------------------------------------------- 1 | s_box = [ 2 | 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 3 | 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 4 | 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 5 | 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 6 | 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 7 | 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 8 | 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 9 | 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 10 | 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 11 | 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 12 | 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 13 | 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 14 | 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 15 | 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 16 | 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 17 | 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 18 | ] 19 | 20 | r_con = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] 21 | 22 | t0 = [ 23 | 0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 24 | 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 25 | 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 26 | 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 27 | 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 28 | 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 29 | 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 30 | 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 31 | 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 32 | 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 33 | 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 34 | 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 35 | 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 36 | 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 37 | 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 38 | 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 39 | 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 40 | 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 41 | 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 42 | 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 43 | 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 44 | 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 45 | 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 46 | 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 47 | 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 48 | 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 49 | 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 50 | 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 51 | 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 52 | 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 53 | 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 54 | 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 55 | 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 56 | 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 57 | 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 58 | 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 59 | 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 60 | 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 61 | 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 62 | 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 63 | 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 64 | 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 65 | 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 66 | 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 67 | 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 68 | 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 69 | 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 70 | 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 71 | 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 72 | 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 73 | 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 74 | 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 75 | 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 76 | 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 77 | 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 78 | 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 79 | 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 80 | 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 81 | 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 82 | 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 83 | 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 84 | 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 85 | 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 86 | 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a 87 | ] 88 | 89 | t1 = [ 90 | 0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 91 | 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 92 | 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 93 | 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 94 | 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 95 | 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 96 | 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 97 | 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 98 | 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 99 | 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 100 | 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 101 | 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 102 | 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 103 | 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 104 | 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 105 | 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 106 | 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 107 | 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 108 | 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 109 | 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 110 | 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 111 | 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 112 | 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 113 | 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 114 | 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 115 | 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 116 | 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 117 | 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 118 | 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 119 | 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 120 | 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 121 | 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 122 | 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 123 | 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 124 | 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 125 | 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 126 | 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 127 | 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 128 | 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 129 | 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 130 | 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 131 | 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 132 | 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 133 | 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 134 | 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 135 | 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 136 | 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 137 | 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 138 | 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 139 | 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 140 | 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 141 | 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 142 | 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 143 | 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 144 | 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 145 | 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 146 | 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 147 | 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 148 | 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 149 | 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 150 | 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 151 | 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 152 | 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 153 | 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616 154 | ] 155 | 156 | t2 = [ 157 | 0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 158 | 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 159 | 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 160 | 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 161 | 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 162 | 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 163 | 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 164 | 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 165 | 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 166 | 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 167 | 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 168 | 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 169 | 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 170 | 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 171 | 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 172 | 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 173 | 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 174 | 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 175 | 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 176 | 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 177 | 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 178 | 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 179 | 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 180 | 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 181 | 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 182 | 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 183 | 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 184 | 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 185 | 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 186 | 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 187 | 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 188 | 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 189 | 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 190 | 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 191 | 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 192 | 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 193 | 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 194 | 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 195 | 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 196 | 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 197 | 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 198 | 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 199 | 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 200 | 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 201 | 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 202 | 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 203 | 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 204 | 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 205 | 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 206 | 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 207 | 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 208 | 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 209 | 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 210 | 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 211 | 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 212 | 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 213 | 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 214 | 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 215 | 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 216 | 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 217 | 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 218 | 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 219 | 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 220 | 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16 221 | ] 222 | 223 | t3 = [ 224 | 0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 225 | 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 226 | 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 227 | 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 228 | 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 229 | 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 230 | 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 231 | 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 232 | 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 233 | 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 234 | 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 235 | 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 236 | 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 237 | 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 238 | 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 239 | 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 240 | 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 241 | 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 242 | 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 243 | 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 244 | 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 245 | 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 246 | 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 247 | 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 248 | 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 249 | 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 250 | 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 251 | 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 252 | 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 253 | 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 254 | 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 255 | 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 256 | 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 257 | 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 258 | 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 259 | 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 260 | 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 261 | 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 262 | 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 263 | 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 264 | 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 265 | 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 266 | 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 267 | 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 268 | 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 269 | 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 270 | 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 271 | 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 272 | 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 273 | 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 274 | 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 275 | 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 276 | 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 277 | 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 278 | 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 279 | 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 280 | 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 281 | 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 282 | 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 283 | 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 284 | 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 285 | 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 286 | 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 287 | 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c 288 | ] 289 | -------------------------------------------------------------------------------- /expected_round_keys/expected_round_keys_generator.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.key_schedule import KeySchedule 2 | from aes_cipher.constants import s_box 3 | from settings.active_settings import ActiveSettings 4 | 5 | 6 | import copy 7 | import random 8 | 9 | 10 | class ExpectedRoundKeysGenerator: 11 | def __init__(self, state): 12 | self.state = copy.deepcopy(state) 13 | 14 | self.debug = False 15 | 16 | for i in range(len(state)): 17 | for j in range(16): 18 | if 0 != self.state[i][j]: 19 | self.state[i][j] = 0xff 20 | 21 | active_settings = ActiveSettings() 22 | self.key = active_settings.key 23 | self.random_state = active_settings.random_state 24 | 25 | self.plaintext = 0 26 | for i in range(16): 27 | self.plaintext <<= 8 28 | 29 | # 1. Fill with zeros 30 | # self.plaintext += random.getrandbits(8) & self.state[0][i] 31 | 32 | # 2. Fill with random values 33 | # ''' 34 | if self.state[0][i]: 35 | self.plaintext += random.getrandbits(8) 36 | else: 37 | self.plaintext += self.random_state[i] 38 | # ''' 39 | 40 | self.round_keys = [[0 for i in range(16)] for j in range(4)] 41 | 42 | for i in range(len(state)): 43 | for j in range(16): 44 | if 0xff == self.state[i][j]: 45 | self.state[i][j] = 1 46 | 47 | @staticmethod 48 | def multiply(a, b): 49 | p = 0 50 | 51 | for i in range(8): 52 | if 1 == b & 1: 53 | p ^= a 54 | high_bit_set = a & 0x80 55 | a = (a << 1) & 0xff 56 | if 0x80 == high_bit_set: 57 | a ^= 0x1b 58 | b >>= 1 59 | 60 | return p 61 | 62 | def generate(self): 63 | key_schedule = KeySchedule() 64 | key_schedule.run(self.key) 65 | 66 | # Round 0 67 | x0 = (self.plaintext >> 120) & 0xff 68 | x1 = (self.plaintext >> 112) & 0xff 69 | x2 = (self.plaintext >> 104) & 0xff 70 | x3 = (self.plaintext >> 96) & 0xff 71 | 72 | x4 = (self.plaintext >> 88) & 0xff 73 | x5 = (self.plaintext >> 80) & 0xff 74 | x6 = (self.plaintext >> 72) & 0xff 75 | x7 = (self.plaintext >> 64) & 0xff 76 | 77 | x8 = (self.plaintext >> 56) & 0xff 78 | x9 = (self.plaintext >> 48) & 0xff 79 | x10 = (self.plaintext >> 40) & 0xff 80 | x11 = (self.plaintext >> 32) & 0xff 81 | 82 | x12 = (self.plaintext >> 24) & 0xff 83 | x13 = (self.plaintext >> 16) & 0xff 84 | x14 = (self.plaintext >> 8) & 0xff 85 | x15 = (self.plaintext >> 0) & 0xff 86 | 87 | # AddRoundKey 88 | x0 ^= key_schedule.round_keys[0][0] 89 | x1 ^= key_schedule.round_keys[0][1] 90 | x2 ^= key_schedule.round_keys[0][2] 91 | x3 ^= key_schedule.round_keys[0][3] 92 | 93 | x4 ^= key_schedule.round_keys[0][4] 94 | x5 ^= key_schedule.round_keys[0][5] 95 | x6 ^= key_schedule.round_keys[0][6] 96 | x7 ^= key_schedule.round_keys[0][7] 97 | 98 | x8 ^= key_schedule.round_keys[0][8] 99 | x9 ^= key_schedule.round_keys[0][9] 100 | x10 ^= key_schedule.round_keys[0][10] 101 | x11 ^= key_schedule.round_keys[0][11] 102 | 103 | x12 ^= key_schedule.round_keys[0][12] 104 | x13 ^= key_schedule.round_keys[0][13] 105 | x14 ^= key_schedule.round_keys[0][14] 106 | x15 ^= key_schedule.round_keys[0][15] 107 | 108 | # SubBytes 109 | y0 = s_box[x0] 110 | y1 = s_box[x1] 111 | y2 = s_box[x2] 112 | y3 = s_box[x3] 113 | 114 | y4 = s_box[x4] 115 | y5 = s_box[x5] 116 | y6 = s_box[x6] 117 | y7 = s_box[x7] 118 | 119 | y8 = s_box[x8] 120 | y9 = s_box[x9] 121 | y10 = s_box[x10] 122 | y11 = s_box[x11] 123 | 124 | y12 = s_box[x12] 125 | y13 = s_box[x13] 126 | y14 = s_box[x14] 127 | y15 = s_box[x15] 128 | 129 | for i in range(16): 130 | if self.state[0][i]: 131 | self.round_keys[0][i] = key_schedule.round_keys[0][i] 132 | 133 | # Round 1 134 | x16 = self.multiply(y0, 2) ^ self.multiply(y5, 3) ^ y10 ^ y15 135 | x17 = y0 ^ self.multiply(y5, 2) ^ self.multiply(y10, 3) ^ y15 136 | x18 = y0 ^ y5 ^ self.multiply(y10, 2) ^ self.multiply(y15, 3) 137 | x19 = self.multiply(y0, 3) ^ y5 ^ y10 ^ self.multiply(y15, 2) 138 | 139 | x20 = self.multiply(y4, 2) ^ self.multiply(y9, 3) ^ y14 ^ y3 140 | x21 = y4 ^ self.multiply(y9, 2) ^ self.multiply(y14, 3) ^ y3 141 | x22 = y4 ^ y9 ^ self.multiply(y14, 2) ^ self.multiply(y3, 3) 142 | x23 = self.multiply(y4, 3) ^ y9 ^ y14 ^ self.multiply(y3, 2) 143 | 144 | x24 = self.multiply(y8, 2) ^ self.multiply(y13, 3) ^ y2 ^ y7 145 | x25 = y8 ^ self.multiply(y13, 2) ^ self.multiply(y2, 3) ^ y7 146 | x26 = y8 ^ y13 ^ self.multiply(y2, 2) ^ self.multiply(y7, 3) 147 | x27 = self.multiply(y8, 3) ^ y13 ^ y2 ^ self.multiply(y7, 2) 148 | 149 | x28 = self.multiply(y12, 2) ^ self.multiply(y1, 3) ^ y6 ^ y11 150 | x29 = y12 ^ self.multiply(y1, 2) ^ self.multiply(y6, 3) ^ y11 151 | x30 = y12 ^ y1 ^ self.multiply(y6, 2) ^ self.multiply(y11, 3) 152 | x31 = self.multiply(y12, 3) ^ y1 ^ y6 ^ self.multiply(y11, 2) 153 | 154 | # AddRoundKey 155 | x16 ^= key_schedule.round_keys[1][0] 156 | x17 ^= key_schedule.round_keys[1][1] 157 | x18 ^= key_schedule.round_keys[1][2] 158 | x19 ^= key_schedule.round_keys[1][3] 159 | 160 | x20 ^= key_schedule.round_keys[1][4] 161 | x21 ^= key_schedule.round_keys[1][5] 162 | x22 ^= key_schedule.round_keys[1][6] 163 | x23 ^= key_schedule.round_keys[1][7] 164 | 165 | x24 ^= key_schedule.round_keys[1][8] 166 | x25 ^= key_schedule.round_keys[1][9] 167 | x26 ^= key_schedule.round_keys[1][10] 168 | x27 ^= key_schedule.round_keys[1][11] 169 | 170 | x28 ^= key_schedule.round_keys[1][12] 171 | x29 ^= key_schedule.round_keys[1][13] 172 | x30 ^= key_schedule.round_keys[1][14] 173 | x31 ^= key_schedule.round_keys[1][15] 174 | 175 | # SubBytes 176 | y16 = s_box[x16] 177 | y17 = s_box[x17] 178 | y18 = s_box[x18] 179 | y19 = s_box[x19] 180 | 181 | y20 = s_box[x20] 182 | y21 = s_box[x21] 183 | y22 = s_box[x22] 184 | y23 = s_box[x23] 185 | 186 | y24 = s_box[x24] 187 | y25 = s_box[x25] 188 | y26 = s_box[x26] 189 | y27 = s_box[x27] 190 | 191 | y28 = s_box[x28] 192 | y29 = s_box[x29] 193 | y30 = s_box[x30] 194 | y31 = s_box[x31] 195 | 196 | variable_part = [0 for i in range(16)] 197 | 198 | variable_part[0] = \ 199 | self.multiply((1 - self.state[0][0]) * y0, 2) ^ \ 200 | self.multiply((1 - self.state[0][5]) * y5, 3) ^ \ 201 | ((1 - self.state[0][10]) * y10) ^ \ 202 | ((1 - self.state[0][15]) * y15) 203 | variable_part[1] = \ 204 | ((1 - self.state[0][0]) * y0) ^ \ 205 | self.multiply((1 - self.state[0][5]) * y5, 2) ^ \ 206 | self.multiply((1 - self.state[0][10]) * y10, 3) ^ \ 207 | ((1 - self.state[0][15]) * y15) 208 | variable_part[2] = \ 209 | ((1 - self.state[0][0]) * y0) ^ \ 210 | ((1 - self.state[0][5]) * y5) ^ \ 211 | self.multiply((1 - self.state[0][10]) * y10, 2) ^ \ 212 | self.multiply((1 - self.state[0][15]) * y15, 3) 213 | variable_part[3] = \ 214 | self.multiply((1 - self.state[0][0]) * y0, 3) ^ \ 215 | ((1 - self.state[0][5]) * y5) ^ \ 216 | ((1 - self.state[0][10]) * y10) ^ \ 217 | self.multiply((1 - self.state[0][15]) * y15, 2) 218 | 219 | variable_part[4] = \ 220 | self.multiply((1 - self.state[0][4]) * y4, 2) ^ \ 221 | self.multiply((1 - self.state[0][9]) * y9, 3) ^ \ 222 | ((1 - self.state[0][14]) * y14) ^ \ 223 | ((1 - self.state[0][3]) * y3) 224 | variable_part[5] = \ 225 | ((1 - self.state[0][4]) * y4) ^ \ 226 | self.multiply((1 - self.state[0][9]) * y9, 2) ^ \ 227 | self.multiply((1 - self.state[0][14]) * y14, 3) ^ \ 228 | ((1 - self.state[0][3]) * y3) 229 | variable_part[6] = \ 230 | ((1 - self.state[0][4]) * y4) ^ \ 231 | ((1 - self.state[0][9]) * y9) ^ \ 232 | self.multiply((1 - self.state[0][14]) * y14, 2) ^ \ 233 | self.multiply((1 - self.state[0][3]) * y3, 3) 234 | variable_part[7] = \ 235 | self.multiply((1 - self.state[0][4]) * y4, 3) ^ \ 236 | ((1 - self.state[0][9]) * y9) ^ \ 237 | ((1 - self.state[0][14]) * y14) ^ \ 238 | self.multiply((1 - self.state[0][3]) * y3, 2) 239 | 240 | variable_part[8] = \ 241 | self.multiply((1 - self.state[0][8]) * y8, 2) ^ \ 242 | self.multiply((1 - self.state[0][13]) * y13, 3) ^ \ 243 | ((1 - self.state[0][2]) * y2) ^ \ 244 | ((1 - self.state[0][7]) * y7) 245 | variable_part[9] = \ 246 | ((1 - self.state[0][8]) * y8) ^ \ 247 | self.multiply((1 - self.state[0][13]) * y13, 2) ^ \ 248 | self.multiply((1 - self.state[0][2]) * y2, 3) ^ \ 249 | ((1 - self.state[0][7]) * y7) 250 | variable_part[10] = \ 251 | ((1 - self.state[0][8]) * y8) ^ \ 252 | ((1 - self.state[0][13]) * y13) ^ \ 253 | self.multiply((1 - self.state[0][2]) * y2, 2) ^ \ 254 | self.multiply((1 - self.state[0][7]) * y7, 3) 255 | variable_part[11] = \ 256 | self.multiply((1 - self.state[0][8]) * y8, 3) ^ \ 257 | ((1 - self.state[0][13]) * y13) ^ \ 258 | (1 - self.state[0][2]) * y2 ^ \ 259 | self.multiply((1 - self.state[0][7]) * y7, 2) 260 | 261 | variable_part[12] = \ 262 | self.multiply((1 - self.state[0][12]) * y12, 2) ^ \ 263 | self.multiply((1 - self.state[0][1]) * y1, 3) ^ \ 264 | ((1 - self.state[0][6]) * y6) ^ \ 265 | ((1 - self.state[0][11]) * y11) 266 | variable_part[13] = \ 267 | ((1 - self.state[0][12]) * y12) ^ \ 268 | self.multiply((1 - self.state[0][1]) * y1, 2) ^ \ 269 | self.multiply((1 - self.state[0][6]) * y6, 3) ^ \ 270 | ((1 - self.state[0][11]) * y11) 271 | variable_part[14] = \ 272 | ((1 - self.state[0][12]) * y12) ^ \ 273 | ((1 - self.state[0][1]) * y1) ^ \ 274 | self.multiply((1 - self.state[0][6]) * y6, 2) ^ \ 275 | self.multiply((1 - self.state[0][11]) * y11, 3) 276 | variable_part[15] = \ 277 | self.multiply((1 - self.state[0][12]) * y12, 3) ^ \ 278 | ((1 - self.state[0][1]) * y1) ^ \ 279 | ((1 - self.state[0][6]) * y6) ^ \ 280 | self.multiply((1 - self.state[0][11]) * y11, 2) 281 | 282 | for i in range(16): 283 | if self.state[1][i]: 284 | self.round_keys[1][i] = key_schedule.round_keys[1][i] ^ variable_part[i] 285 | 286 | # Round 2 287 | variable_part = [0 for i in range(16)] 288 | 289 | variable_part[0] = \ 290 | self.multiply((1 - self.state[1][0]) * y16, 2) ^ \ 291 | self.multiply((1 - self.state[1][5]) * y21, 3) ^ \ 292 | ((1 - self.state[1][10]) * y26) ^ \ 293 | ((1 - self.state[1][15]) * y31) 294 | variable_part[1] = \ 295 | ((1 - self.state[1][0]) * y16) ^ \ 296 | self.multiply((1 - self.state[1][5]) * y21, 2) ^ \ 297 | self.multiply((1 - self.state[1][10]) * y26, 3) ^ \ 298 | ((1 - self.state[1][15]) * y31) 299 | variable_part[2] = \ 300 | ((1 - self.state[1][0]) * y16) ^ \ 301 | ((1 - self.state[1][5]) * y21) ^ \ 302 | self.multiply((1 - self.state[1][10]) * y26, 2) ^ \ 303 | self.multiply((1 - self.state[1][15]) * y31, 3) 304 | variable_part[3] = \ 305 | self.multiply((1 - self.state[1][0]) * y16, 3) ^ \ 306 | ((1 - self.state[1][5]) * y21) ^ \ 307 | ((1 - self.state[1][10]) * y26) ^ \ 308 | self.multiply((1 - self.state[1][15]) * y31, 2) 309 | 310 | variable_part[4] = \ 311 | self.multiply((1 - self.state[1][4]) * y20, 2) ^ \ 312 | self.multiply((1 - self.state[1][9]) * y25, 3) ^ \ 313 | ((1 - self.state[1][14]) * y30) ^ \ 314 | ((1 - self.state[1][3]) * y19) 315 | variable_part[5] = \ 316 | ((1 - self.state[1][4]) * y20) ^ \ 317 | self.multiply((1 - self.state[1][9]) * y25, 2) ^ \ 318 | self.multiply((1 - self.state[1][14]) * y30, 3) ^ \ 319 | ((1 - self.state[1][3]) * y19) 320 | variable_part[6] = \ 321 | ((1 - self.state[1][4]) * y20) ^ \ 322 | ((1 - self.state[1][9]) * y25) ^ \ 323 | self.multiply((1 - self.state[1][14]) * y30, 2) ^ \ 324 | self.multiply((1 - self.state[1][3]) * y19, 3) 325 | variable_part[7] = \ 326 | self.multiply((1 - self.state[1][4]) * y20, 3) ^ \ 327 | ((1 - self.state[1][9]) * y25) ^ \ 328 | ((1 - self.state[1][14]) * y30) ^ \ 329 | self.multiply((1 - self.state[1][3]) * y19, 2) 330 | 331 | variable_part[8] = \ 332 | self.multiply((1 - self.state[1][8]) * y24, 2) ^ \ 333 | self.multiply((1 - self.state[1][13]) * y29, 3) ^ \ 334 | ((1 - self.state[1][2]) * y18) ^ \ 335 | ((1 - self.state[1][7]) * y23) 336 | variable_part[9] = \ 337 | ((1 - self.state[1][8]) * y24) ^ \ 338 | self.multiply((1 - self.state[1][13]) * y29, 2) ^ \ 339 | self.multiply((1 - self.state[1][2]) * y18, 3) ^ \ 340 | ((1 - self.state[1][7]) * y23) 341 | variable_part[10] = \ 342 | ((1 - self.state[1][8]) * y24) ^ \ 343 | ((1 - self.state[1][13]) * y29) ^ \ 344 | self.multiply((1 - self.state[1][2]) * y18, 2) ^ \ 345 | self.multiply((1 - self.state[1][7]) * y23, 3) 346 | variable_part[11] = \ 347 | self.multiply((1 - self.state[1][8]) * y24, 3) ^ \ 348 | ((1 - self.state[1][13]) * y29) ^ \ 349 | ((1 - self.state[1][2]) * y18) ^ \ 350 | self.multiply((1 - self.state[1][7]) * y23, 2) 351 | 352 | variable_part[12] = \ 353 | self.multiply((1 - self.state[1][12]) * y28, 2) ^ \ 354 | self.multiply((1 - self.state[1][1]) * y17, 3) ^ \ 355 | ((1 - self.state[1][6]) * y22) ^ \ 356 | ((1 - self.state[1][11]) * y27) 357 | variable_part[13] = \ 358 | ((1 - self.state[1][12]) * y28) ^ \ 359 | self.multiply((1 - self.state[1][1]) * y17, 2) ^ \ 360 | self.multiply((1 - self.state[1][6]) * y22, 3) ^ \ 361 | ((1 - self.state[1][11]) * y27) 362 | variable_part[14] = \ 363 | ((1 - self.state[1][12]) * y28) ^ \ 364 | ((1 - self.state[1][1]) * y17) ^ \ 365 | self.multiply((1 - self.state[1][6]) * y22, 2) ^ \ 366 | self.multiply((1 - self.state[1][11]) * y27, 3) 367 | variable_part[15] = \ 368 | self.multiply((1 - self.state[1][12]) * y28, 3) ^ \ 369 | ((1 - self.state[1][1]) * y17) ^ \ 370 | ((1 - self.state[1][6]) * y22) ^ \ 371 | self.multiply((1 - self.state[1][11]) * y27, 2) 372 | 373 | for i in range(16): 374 | if self.state[2][i]: 375 | self.round_keys[2][i] = key_schedule.round_keys[2][i] ^ variable_part[i] 376 | 377 | # Round 3 378 | self.round_keys[3][0] = key_schedule.round_keys[3][0] 379 | self.round_keys[3][1] = key_schedule.round_keys[3][1] 380 | self.round_keys[3][2] = key_schedule.round_keys[3][2] 381 | self.round_keys[3][3] = key_schedule.round_keys[3][3] 382 | 383 | self.round_keys[3][4] = key_schedule.round_keys[3][4] 384 | self.round_keys[3][5] = key_schedule.round_keys[3][5] 385 | self.round_keys[3][6] = key_schedule.round_keys[3][6] 386 | self.round_keys[3][7] = key_schedule.round_keys[3][7] 387 | 388 | self.round_keys[3][8] = key_schedule.round_keys[3][8] 389 | self.round_keys[3][9] = key_schedule.round_keys[3][9] 390 | self.round_keys[3][10] = key_schedule.round_keys[3][10] 391 | self.round_keys[3][11] = key_schedule.round_keys[3][11] 392 | 393 | self.round_keys[3][12] = key_schedule.round_keys[3][12] 394 | self.round_keys[3][13] = key_schedule.round_keys[3][13] 395 | self.round_keys[3][14] = key_schedule.round_keys[3][14] 396 | self.round_keys[3][15] = key_schedule.round_keys[3][15] 397 | 398 | if self.debug: 399 | for i in range(4): 400 | print('{:2}: '.format(i), end='') 401 | for j in range(16): 402 | print('{} '.format(format(self.round_keys[i][j], '02x')), end='') 403 | print() 404 | 405 | print() 406 | print() 407 | 408 | for i in range(4): 409 | print('{:2}: '.format(i), end='') 410 | print('[ ', end='') 411 | for j in range(16): 412 | print('0x{}, '.format(format(self.round_keys[i][j], '02x')), end='') 413 | print(']', end='') 414 | print() 415 | 416 | round_keys = [] 417 | for i in range(4): 418 | for j in range(16): 419 | round_keys.append(self.round_keys[i][j]) 420 | 421 | return round_keys 422 | -------------------------------------------------------------------------------- /cpa_attacker/attacker.py: -------------------------------------------------------------------------------- 1 | from aes_cipher.constants import s_box, t0, t1, t2, t3 2 | from cpa_attacker.plotter import Plotter 3 | from cpa_attacker.round1 import Round1 4 | from cpa_attacker.round2 import Round2 5 | from cpa_attacker.round3 import Round3 6 | from leakage_generator.generator import Generator 7 | from leakage_model.hw_s_box import HwSBox 8 | from leakage_model.hw_t_table import HwTTable 9 | from expected_round_keys.expected_round_keys_generator import ExpectedRoundKeysGenerator 10 | from symbolic_evaluator.evaluation_case_solver import EvaluationCaseSolver 11 | 12 | 13 | import gc 14 | import math 15 | import numpy 16 | import operator 17 | import pickle 18 | import shutil 19 | import time 20 | 21 | 22 | class Attacker: 23 | def __init__(self, generate_traces=True, t_tables_implementation=False, debug=False): 24 | self.t_tables_implementation = t_tables_implementation 25 | if self.t_tables_implementation: 26 | self.power_model = HwTTable() 27 | else: 28 | self.power_model = HwSBox() 29 | 30 | self.path = './data/' 31 | self.source_plaintexts_file = self.path + 'plaintexts.bin' 32 | self.source_traces_file = self.path + 'traces.npy' 33 | 34 | self.plaintexts_file_format = self.path + 'plaintexts_evaluation_case_{:02}_experiment_{:03}.bin' 35 | self.traces_file_format = self.path + 'traces_evaluation_case_{:02}_experiment_{:03}.npy' 36 | 37 | self.number_of_plaintexts = 0 38 | self.plaintexts = None 39 | 40 | self.start_sample = 0 41 | if t_tables_implementation: 42 | self.number_of_samples = 16 * 9 43 | else: 44 | self.number_of_samples = 16 * 9 45 | 46 | self.traces = None 47 | 48 | self.subkey_size = 8 49 | 50 | self.average_traces = None 51 | self.average_traces_count = None 52 | 53 | self.expected_key = None 54 | 55 | self.round1 = None 56 | self.round2 = None 57 | self.round3 = None 58 | 59 | self.recovered_keys = None 60 | self.valid_recovered_keys = None 61 | self.guessing_entropy = None 62 | 63 | self.number_of_cpa_attacks = 0 64 | 65 | self.debug = debug 66 | 67 | self.plotter_possible_key = [-1] * 64 68 | self.plot_correlation_matrix = False 69 | 70 | self.number_of_traces = 500 71 | 72 | self.attacked_number_of_rounds = 0 73 | 74 | self.generate_traces = generate_traces 75 | 76 | self.conditional_average = True 77 | 78 | self.round_leakage = True 79 | 80 | numpy.seterr(divide='ignore', invalid='ignore') 81 | 82 | @staticmethod 83 | def pcc(p, o): 84 | n = p.size 85 | do = o - (numpy.einsum('ij->j', o) / numpy.double(n)) 86 | p -= (numpy.einsum('i->', p) / numpy.double(n)) 87 | tmp = numpy.einsum('ij,ij->j', do, do) 88 | tmp *= numpy.einsum('i,i->', p, p) 89 | return numpy.dot(p, do) / numpy.sqrt(tmp) 90 | 91 | @staticmethod 92 | def get_keys(correlation_matrix): 93 | max_value_indexes = numpy.argwhere(correlation_matrix == numpy.amax(correlation_matrix)) 94 | 95 | subkeys = [] 96 | for max_value_index in max_value_indexes: 97 | subkeys.append(max_value_index[0]) 98 | 99 | return subkeys 100 | 101 | @staticmethod 102 | def get_keys2(correlation_matrix): 103 | subkeys = [] 104 | 105 | max_value_index = numpy.argmax(correlation_matrix) 106 | subkey = numpy.unravel_index(max_value_index, correlation_matrix.shape)[0] 107 | 108 | subkeys.append(subkey) 109 | 110 | old_correlation_coefficient = correlation_matrix[subkey, :] 111 | correlation_matrix[subkey, :] = numpy.zeros((1, correlation_matrix.shape[1])) 112 | 113 | max_value_index = numpy.argmax(correlation_matrix) 114 | subkey = numpy.unravel_index(max_value_index, correlation_matrix.shape)[0] 115 | 116 | subkeys.append(subkey) 117 | 118 | correlation_matrix[subkeys[0], :] = old_correlation_coefficient 119 | 120 | return subkeys 121 | 122 | def predict_power_consumption(self, plaintext, key, index): 123 | value = plaintext ^ key 124 | 125 | if self.t_tables_implementation: 126 | if 0 == index % 4: 127 | value = t0[value] 128 | elif 1 == index % 4: 129 | value = t1[value] 130 | elif 2 == index % 4: 131 | value = t2[value] 132 | elif 3 == index % 4: 133 | value = t3[value] 134 | else: 135 | value = s_box[value] 136 | 137 | return self.power_model.leak(value) 138 | 139 | def get_plaintext_part(self, plaintext, index): 140 | if (0 <= index) & (15 >= index): 141 | # first round 142 | x = (plaintext >> ((15 - index) * 8)) & 0xff 143 | elif (16 <= index) & (31 >= index): 144 | # second round 145 | x = self.round1.get_plaintext_part(plaintext, index) 146 | elif (32 <= index) & (47 >= index): 147 | # third round 148 | x = self.round2.get_plaintext_part(plaintext, index) 149 | elif (48 <= index) & (63 >= index): 150 | # fourth round 151 | x = self.round3.get_plaintext_part(plaintext, index) 152 | 153 | return x 154 | 155 | def rank(self, correlation_matrix, expected_key): 156 | correlation_coefficients = [0] * (2 ** self.subkey_size) 157 | 158 | for i in range(correlation_matrix.shape[0]): 159 | max_value_index = numpy.argmax(correlation_matrix[i]) 160 | max_value = correlation_matrix[i][max_value_index] 161 | correlation_coefficients[i] = (i, max_value, max_value_index) 162 | 163 | correlation_coefficients = sorted(correlation_coefficients, key=operator.itemgetter(1), reverse=True) 164 | 165 | rank_index = -1 166 | rank = 10 167 | expected_key_rank = rank_index 168 | break_next = False 169 | for i in range(len(correlation_coefficients)): 170 | key = correlation_coefficients[i][0] 171 | value = correlation_coefficients[i][1] 172 | sample = correlation_coefficients[i][2] 173 | 174 | if value != rank: 175 | rank_index += 1 176 | rank = value 177 | # print('Rank {}: 0x{} {} ({})'.format(rank_index, format(key, '02x'), value, sample)) 178 | if break_next: 179 | break 180 | if key == expected_key: 181 | expected_key_rank = rank_index 182 | break_next = True 183 | else: 184 | # print('Rank {}: 0x{} {} ({})'.format(rank_index, format(key, '02x'), value, sample)) 185 | if key == expected_key: 186 | expected_key_rank = rank_index 187 | break_next = True 188 | 189 | return expected_key_rank 190 | 191 | def delta(self, correlation_matrix): 192 | correlation_coefficients = [0] * (2 ** self.subkey_size) 193 | 194 | for i in range(correlation_matrix.shape[0]): 195 | max_value_index = numpy.argmax(correlation_matrix[i]) 196 | max_value = correlation_matrix[i][max_value_index] 197 | correlation_coefficients[i] = (i, max_value, max_value_index) 198 | 199 | correlation_coefficients = sorted(correlation_coefficients, key=operator.itemgetter(1), reverse=True) 200 | 201 | first_value = correlation_coefficients[0][1] 202 | second_value = correlation_coefficients[1][1] 203 | delta = first_value - second_value 204 | 205 | return delta 206 | 207 | def init_conditional_average(self, index): 208 | self.start_sample = 0 209 | 210 | # all rounds 211 | if self.t_tables_implementation: 212 | self.number_of_samples = 16 * 9 213 | else: 214 | self.number_of_samples = 16 * 9 215 | 216 | # first 4 rounds 217 | # self.number_of_samples = 16 * 4 218 | 219 | # just 1 round 220 | if self.round_leakage: 221 | self.number_of_samples = 16 222 | 223 | self.average_traces = numpy.zeros((2 ** self.subkey_size, self.number_of_samples)) 224 | self.average_traces_count = [0 for i in range(2 ** self.subkey_size)] 225 | 226 | self.number_of_plaintexts = 2 ** self.subkey_size 227 | self.plaintexts = [i for i in range(self.number_of_plaintexts)] 228 | 229 | def load_conditional_average(self, index, start, number_of_traces, evaluation_case, experiment): 230 | plaintexts_file = self.plaintexts_file_format.format(evaluation_case, experiment) 231 | traces_file = self.traces_file_format.format(evaluation_case, experiment) 232 | 233 | f = open(plaintexts_file, 'rb') 234 | plaintexts = pickle.load(f) 235 | number_of_plaintexts = len(plaintexts) 236 | f.close() 237 | 238 | traces = numpy.load(traces_file) 239 | 240 | if not self.round_leakage: 241 | traces = traces[:, self.start_sample:self.start_sample + self.number_of_samples] 242 | 243 | # Use just the leakage from the attacked round 244 | if self.round_leakage: 245 | if index in range(16): 246 | traces = traces[:, 0:16] 247 | elif index in range(16, 32, 1): 248 | traces = traces[:, 16:32] 249 | elif index in range(32, 48, 1): 250 | traces = traces[:, 32:48] 251 | else: 252 | traces = traces[:, 48:64] 253 | 254 | if self.conditional_average: 255 | # Conditional average 256 | for j in range(start, number_of_traces, 1): 257 | x = self.get_plaintext_part(plaintexts[j], index) 258 | self.average_traces_count[x] += 1 259 | self.average_traces[x] += (traces[j] - self.average_traces[x]) / self.average_traces_count[x] 260 | 261 | self.traces = self.average_traces 262 | 263 | valid_plaintexts = 0 264 | for i in range(2 ** self.subkey_size): 265 | if self.average_traces[i][0]: 266 | valid_plaintexts += 1 267 | 268 | if self.number_of_plaintexts != valid_plaintexts: 269 | self.number_of_plaintexts = valid_plaintexts 270 | new_plaintexts = [0 for i in range(self.number_of_plaintexts)] 271 | new_traces = numpy.zeros((self.number_of_plaintexts, self.number_of_samples)) 272 | 273 | index = 0 274 | for i in range(2 ** self.subkey_size): 275 | if self.average_traces[i][0]: 276 | new_plaintexts[index] = self.plaintexts[i] 277 | new_traces[index] = self.average_traces[i] 278 | index += 1 279 | 280 | self.plaintexts = new_plaintexts 281 | self.traces = new_traces 282 | else: 283 | # No conditional average 284 | self.number_of_plaintexts = number_of_plaintexts 285 | self.plaintexts = [0 for i in range(self.number_of_plaintexts)] 286 | for j in range(start, number_of_traces, 1): 287 | self.plaintexts[j] = self.get_plaintext_part(plaintexts[j], index) 288 | self.traces = traces 289 | 290 | def conditional_average_attack(self, index, number_of_traces): 291 | self.number_of_cpa_attacks += 1 292 | 293 | hypothetical_power_consumption = numpy.zeros((self.number_of_plaintexts, 2 ** self.subkey_size)) 294 | 295 | for i in range(self.number_of_plaintexts): 296 | x = self.plaintexts[i] 297 | 298 | for j in range(2 ** self.subkey_size): 299 | power = self.predict_power_consumption(x, j, index) 300 | hypothetical_power_consumption[i][j] = power 301 | 302 | correlation_matrix = numpy.zeros((2 ** self.subkey_size, self.number_of_samples)) 303 | 304 | for i in range(2 ** self.subkey_size): 305 | pcc = self.pcc(hypothetical_power_consumption[:, i], self.traces) 306 | correlation_matrix[i] = pcc 307 | 308 | correlation_matrix = numpy.nan_to_num(correlation_matrix) 309 | 310 | recovered_keys = self.get_keys(correlation_matrix) 311 | 312 | expected_key = self.expected_key[index] 313 | 314 | rank = self.rank(correlation_matrix, expected_key) 315 | 316 | guessing_entropy = self.get_guessing_entropy(index, rank) 317 | 318 | if self.plot_correlation_matrix: 319 | self.plotter_possible_key[index] += 1 320 | Plotter.plot_correlation_matrix(correlation_matrix, index, expected_key, self.plotter_possible_key[index]) 321 | 322 | return recovered_keys, guessing_entropy 323 | 324 | def conditional_average_attack2(self, index, number_of_traces): 325 | self.number_of_cpa_attacks += 1 326 | 327 | hypothetical_power_consumption = numpy.zeros((self.number_of_plaintexts, 2 ** self.subkey_size)) 328 | 329 | for i in range(self.number_of_plaintexts): 330 | x = self.plaintexts[i] 331 | 332 | for j in range(2 ** self.subkey_size): 333 | power = self.predict_power_consumption(x, j, index) 334 | hypothetical_power_consumption[i][j] = power 335 | 336 | correlation_matrix = numpy.zeros((2 ** self.subkey_size, self.number_of_samples)) 337 | 338 | for i in range(2 ** self.subkey_size): 339 | pcc = self.pcc(hypothetical_power_consumption[:, i], self.traces) 340 | correlation_matrix[i] = pcc 341 | 342 | correlation_matrix = numpy.nan_to_num(correlation_matrix) 343 | 344 | recovered_keys = self.get_keys2(correlation_matrix) 345 | 346 | expected_key = self.expected_key[index] 347 | 348 | rank = self.rank(correlation_matrix, expected_key) 349 | 350 | guessing_entropy = self.get_guessing_entropy(index, rank) 351 | 352 | if self.plot_correlation_matrix: 353 | self.plotter_possible_key[index] += 1 354 | Plotter.plot_correlation_matrix(correlation_matrix, index, expected_key, self.plotter_possible_key[index]) 355 | 356 | return recovered_keys 357 | 358 | def conditional_average_attack_delta(self, index, number_of_traces): 359 | self.number_of_cpa_attacks += 1 360 | 361 | hypothetical_power_consumption = numpy.zeros((self.number_of_plaintexts, 2 ** self.subkey_size)) 362 | 363 | for i in range(self.number_of_plaintexts): 364 | x = self.plaintexts[i] 365 | 366 | for j in range(2 ** self.subkey_size): 367 | power = self.predict_power_consumption(x, j, index) 368 | hypothetical_power_consumption[i][j] = power 369 | 370 | correlation_matrix = numpy.zeros((2 ** self.subkey_size, self.number_of_samples)) 371 | 372 | for i in range(2 ** self.subkey_size): 373 | pcc = self.pcc(hypothetical_power_consumption[:, i], self.traces) 374 | correlation_matrix[i] = pcc 375 | 376 | correlation_matrix = numpy.nan_to_num(correlation_matrix) 377 | 378 | recovered_keys = self.get_keys(correlation_matrix) 379 | 380 | expected_key = self.expected_key[index] 381 | 382 | rank = self.rank(correlation_matrix, expected_key) 383 | delta = self.delta(correlation_matrix) 384 | 385 | guessing_entropy = self.get_guessing_entropy(index, rank) 386 | 387 | if self.plot_correlation_matrix: 388 | self.plotter_possible_key[index] += 1 389 | Plotter.plot_correlation_matrix(correlation_matrix, index, expected_key, self.plotter_possible_key[index]) 390 | 391 | return recovered_keys, delta, guessing_entropy 392 | 393 | def get_guessing_entropy(self, index, rank): 394 | if (self.attacked_number_of_rounds - 1) * 16 <= index < self.attacked_number_of_rounds * 16: 395 | return math.log(rank + 1, 2) 396 | 397 | return 0 398 | 399 | def attack_subkey(self, index, evaluation_case, experiment): 400 | self.init_conditional_average(index) 401 | self.load_conditional_average(index, 0, self.number_of_traces, evaluation_case, experiment) 402 | keys, guessing_entropy = self.conditional_average_attack(index, self.number_of_traces) 403 | 404 | self.traces = None 405 | self.plaintexts = None 406 | gc.collect() 407 | 408 | return keys[0], guessing_entropy 409 | 410 | def attack_subkey2(self, index, evaluation_case, experiment): 411 | self.init_conditional_average(index) 412 | self.load_conditional_average(index, 0, self.number_of_traces, evaluation_case, experiment) 413 | keys = self.conditional_average_attack2(index, self.number_of_traces) 414 | 415 | self.traces = None 416 | self.plaintexts = None 417 | gc.collect() 418 | 419 | return keys 420 | 421 | def attack_subkey_delta(self, index, evaluation_case, experiment): 422 | self.init_conditional_average(index) 423 | self.load_conditional_average(index, 0, self.number_of_traces, evaluation_case, experiment) 424 | keys, delta, guessing_entropy = self.conditional_average_attack_delta(index, self.number_of_traces) 425 | 426 | self.traces = None 427 | self.plaintexts = None 428 | gc.collect() 429 | 430 | return keys[0], delta, guessing_entropy 431 | 432 | @staticmethod 433 | def get_pair_indexes(pairs, pair, round_number): 434 | indexes = [] 435 | 436 | for i in range(16): 437 | if pair in set(pairs[i]): 438 | indexes.append(16 * round_number + i) 439 | 440 | return indexes 441 | 442 | def check_recovery(self, number_of_possible_keys, number_of_rounds): 443 | if self.debug: 444 | print('INDEX') 445 | print('IDX ', end='') 446 | for i in range(16 * number_of_rounds): 447 | print('{:2} '.format(i), end='') 448 | print() 449 | 450 | print('RECOVERED') 451 | for i in range(number_of_possible_keys): 452 | print('{:2}) '.format(i), end='') 453 | for j in range(16 * number_of_rounds): 454 | if self.recovered_keys[i][j] is not None: 455 | print('{} '.format(format(self.recovered_keys[i][j], '02x')), end='') 456 | else: 457 | print('{} '.format(format(0x00, '02x')), end='') 458 | print(' {}'.format(self.valid_recovered_keys[i]), end='') 459 | print() 460 | print() 461 | 462 | print('EXPECTED') 463 | print('EXP ', end='') 464 | for i in range(16 * number_of_rounds): 465 | print('{} '.format(format(self.expected_key[i], '02x')), end='') 466 | print() 467 | 468 | correct_key_index = -1 469 | 470 | valid_keys = 0 471 | for i in range(number_of_possible_keys): 472 | if self.valid_recovered_keys[i]: 473 | valid_keys += 1 474 | 475 | found = True 476 | for j in range(16 * number_of_rounds): 477 | if self.recovered_keys[i][j] != self.expected_key[j]: 478 | found = False 479 | break 480 | 481 | if found: 482 | correct_key_index = i 483 | 484 | if self.debug and found: 485 | print('Correct key at index {}.'.format(i)) 486 | 487 | if self.debug and 1 == valid_keys: 488 | print('Unique candidate!') 489 | 490 | if 1 == valid_keys: 491 | return correct_key_index 492 | else: 493 | return -1 494 | 495 | def attack(self, initial_state, number_of_traces, evaluation_case, experiment): 496 | self.number_of_traces = number_of_traces 497 | self.guessing_entropy = 0 498 | self.number_of_cpa_attacks = 0 499 | 500 | evaluation_case_solver = EvaluationCaseSolver(initial_state) 501 | evaluation_case_solver.process() 502 | state = evaluation_case_solver.state 503 | pairs = evaluation_case_solver.pairs 504 | statistics = evaluation_case_solver.get_statistics() 505 | max_possible_keys = evaluation_case_solver.get_max_possible_keys() 506 | if self.debug: 507 | evaluation_case_solver.print_state_pairs() 508 | 509 | if self.debug: 510 | print('Attack {} round(s) to get {} possible key(s).'.format(statistics[1], statistics[0])) 511 | 512 | self.attacked_number_of_rounds = statistics[1] 513 | 514 | known_pairs = set() 515 | map_pairs = [] 516 | 517 | self.recovered_keys = [[0 for i in range(64)] for j in range(max_possible_keys)] 518 | self.valid_recovered_keys = [True for i in range(max_possible_keys)] 519 | self.guessing_entropy = [0 for i in range(max_possible_keys)] 520 | 521 | for i in range(statistics[1]): 522 | if 1 == i: 523 | self.round1 = Round1(self.recovered_keys[0], state) 524 | if 2 == i: 525 | self.round2 = Round2(self.recovered_keys[0], state) 526 | if 3 == i: 527 | self.round3 = Round3(self.recovered_keys[0], state) 528 | 529 | for j in range(16): 530 | if 0 != state[i][j]: 531 | index = 16 * i + j 532 | if self.debug: 533 | print('Attack subkey: {:2}'.format(index)) 534 | 535 | subkey_pairs = set(pairs[i][j]) 536 | 537 | if set(subkey_pairs) <= set(known_pairs): 538 | 539 | if 0 == len(pairs[i][j]): 540 | recovered_key, guessing_entropy = self.attack_subkey(index, evaluation_case, experiment) 541 | for k in range(max_possible_keys): 542 | self.recovered_keys[k][index] = recovered_key 543 | self.guessing_entropy[k] += guessing_entropy 544 | else: 545 | is_index_mapped = False 546 | for k in range(len(pairs[i][j])): 547 | if index in map_pairs[pairs[i][j][k] - 1]: 548 | is_index_mapped = True 549 | break 550 | 551 | if not is_index_mapped: 552 | recovered_key = [None for i in range(32)] 553 | delta = [0 for i in range(32)] 554 | guessing_entropy = [0 for i in range(32)] 555 | 556 | mask = 0 557 | for pair in subkey_pairs: 558 | mask |= 2 ** (pair - 1) 559 | 560 | for k in range(max_possible_keys): 561 | if recovered_key[k & mask] is None and self.valid_recovered_keys[k]: 562 | self.round2 = Round2(self.recovered_keys[k], state) 563 | self.round3 = Round3(self.recovered_keys[k], state) 564 | 565 | recovered_key[k & mask], delta[k & mask], guessing_entropy[k & mask] = \ 566 | self.attack_subkey_delta(index, evaluation_case, experiment) 567 | 568 | self.recovered_keys[k][index] = recovered_key[k & mask] 569 | self.guessing_entropy[k] += guessing_entropy[k & mask] 570 | 571 | if (1 == abs(state[i][j])) and (0 != len(pairs[i][j])): 572 | max_delta = -1 573 | for k in range(max_possible_keys): 574 | if max_delta < delta[k & mask]: 575 | max_delta = delta[k & mask] 576 | 577 | for k in range(max_possible_keys): 578 | if max_delta > delta[k & mask]: 579 | self.valid_recovered_keys[k] = False 580 | else: 581 | if 1 == len(subkey_pairs): 582 | pair = list(subkey_pairs)[0] 583 | 584 | [index1, index2] = self.get_pair_indexes(pairs[i], pair, i) 585 | recovered_keys = self.attack_subkey2(index, evaluation_case, experiment) 586 | 587 | mask = 2 ** (pair - 1) 588 | for k in range(max_possible_keys): 589 | if 0 == k & mask: 590 | self.recovered_keys[k][index1] = recovered_keys[0] 591 | self.recovered_keys[k][index2] = recovered_keys[1] 592 | else: 593 | self.recovered_keys[k][index1] = recovered_keys[1] 594 | self.recovered_keys[k][index2] = recovered_keys[0] 595 | 596 | elif 2 == len(subkey_pairs): 597 | pair1 = list(subkey_pairs)[0] 598 | pair2 = list(subkey_pairs)[1] 599 | 600 | if set([pair1]) <= set(known_pairs): 601 | new_pair = pair2 602 | known_pair = pair1 603 | else: 604 | new_pair = pair1 605 | known_pair = pair2 606 | 607 | [index1, index2] = self.get_pair_indexes(pairs[i], new_pair, i) 608 | 609 | direct = None 610 | reverse = None 611 | 612 | known_mask = 2 ** (known_pair - 1) 613 | mask = 2 ** (new_pair - 1) 614 | for k in range(max_possible_keys): 615 | if 0 == k & known_mask: 616 | if direct is None: 617 | self.round1 = Round1(self.recovered_keys[k], state) 618 | self.round2 = Round2(self.recovered_keys[k], state) 619 | direct = self.attack_subkey2(index, evaluation_case, experiment) 620 | 621 | if 0 == k & mask: 622 | self.recovered_keys[k][index1] = direct[0] 623 | self.recovered_keys[k][index2] = direct[1] 624 | else: 625 | self.recovered_keys[k][index1] = direct[1] 626 | self.recovered_keys[k][index2] = direct[0] 627 | else: 628 | if reverse is None: 629 | self.round1 = Round1(self.recovered_keys[k], state) 630 | self.round2 = Round2(self.recovered_keys[k], state) 631 | reverse = self.attack_subkey2(index, evaluation_case, experiment) 632 | 633 | if 0 == k & mask: 634 | self.recovered_keys[k][index1] = reverse[0] 635 | self.recovered_keys[k][index2] = reverse[1] 636 | else: 637 | self.recovered_keys[k][index1] = reverse[1] 638 | self.recovered_keys[k][index2] = reverse[0] 639 | 640 | for pair in subkey_pairs: 641 | if pair not in known_pairs: 642 | known_pairs.add(pair) 643 | map_pairs.append(self.get_pair_indexes(pairs[i], pair, i)) 644 | 645 | correct_key_index = self.check_recovery(max_possible_keys, statistics[1]) 646 | 647 | if self.debug: 648 | print('Number of CPA attacks: {}.'.format(self.number_of_cpa_attacks)) 649 | 650 | return self.guessing_entropy[correct_key_index] 651 | 652 | def dump_data(self, evaluation_case, initial_state, experiments, traces_x, guessing_entropy_y, 653 | minimum_number_of_traces, duration): 654 | f = open('./output/data_evaluation_case_{:02}.txt'.format(evaluation_case), 'w') 655 | 656 | f.write('Evaluation case: {}\n'.format(evaluation_case)) 657 | f.write('Experiments: {}\n'.format(experiments)) 658 | 659 | f.write('\n') 660 | 661 | f.write('Initial state: {}\n'.format(initial_state)) 662 | f.write('Attacked number of rounds: {}\n'.format(self.attacked_number_of_rounds)) 663 | f.write('CPA attacks: {}\n'.format(self.number_of_cpa_attacks)) 664 | 665 | f.write('\n') 666 | 667 | f.write('Traces: {}\n'.format(traces_x)) 668 | f.write('GE: {}\n'.format(guessing_entropy_y)) 669 | f.write('Minimum number of traces: {}'.format(minimum_number_of_traces)) 670 | 671 | f.write('\n') 672 | 673 | f.write('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(duration)))) 674 | 675 | f.close() 676 | 677 | @staticmethod 678 | def get_minimum_number_of_traces(traces_x, guessing_entropy_y): 679 | minimum = -1 680 | 681 | for i in range(len(traces_x) - 1, -1, -1): 682 | if 0 != guessing_entropy_y[i]: 683 | break 684 | minimum = traces_x[i] 685 | 686 | return minimum 687 | 688 | def rename_files(self, evaluation_case, experiment): 689 | if not self.generate_traces: 690 | return 691 | 692 | destination_plaintext_file = self.plaintexts_file_format.format(evaluation_case, experiment) 693 | destination_traces_file = self.traces_file_format.format(evaluation_case, experiment) 694 | 695 | shutil.move(self.source_plaintexts_file, destination_plaintext_file) 696 | shutil.move(self.source_traces_file, destination_traces_file) 697 | 698 | def attack_guessing_entropy(self, evaluation_case, initial_state, start_traces, stop_traces, step_traces, 699 | experiments=1): 700 | evaluation_case_start_time = time.time() 701 | 702 | traces_x = [] 703 | guessing_entropy_y = [] 704 | 705 | for experiment in range(experiments): 706 | # Get attack state 707 | evaluation_case_solver = EvaluationCaseSolver(initial_state) 708 | evaluation_case_solver.process() 709 | state = evaluation_case_solver.state 710 | 711 | if self.generate_traces: 712 | generator = Generator(state, stop_traces + step_traces, self.t_tables_implementation) 713 | generator.generate() 714 | 715 | key_schedule = ExpectedRoundKeysGenerator(state) 716 | self.expected_key = key_schedule.generate() 717 | 718 | # Rename leakage files 719 | self.rename_files(evaluation_case, experiment) 720 | 721 | for traces in range(start_traces, stop_traces + 1, step_traces): 722 | guessing_entropy = self.attack(initial_state, traces, evaluation_case, experiment) 723 | 724 | if 0 == experiment: 725 | traces_x.append(traces) 726 | guessing_entropy_y.append(guessing_entropy) 727 | else: 728 | index = -1 729 | for j in range(len(traces_x)): 730 | if traces_x[j] == traces: 731 | index = j 732 | break 733 | 734 | guessing_entropy_y[index] += (guessing_entropy - guessing_entropy_y[index]) / (traces + 1) 735 | 736 | Plotter.plot_guessing_entropy('{:02}'.format(evaluation_case), traces_x, guessing_entropy_y) 737 | 738 | evaluation_case_stop_time = time.time() 739 | duration = evaluation_case_stop_time - evaluation_case_start_time 740 | 741 | minimum_number_of_traces = self.get_minimum_number_of_traces(traces_x, guessing_entropy_y) 742 | 743 | self.dump_data(evaluation_case, initial_state, experiments, traces_x, guessing_entropy_y, 744 | minimum_number_of_traces, duration) 745 | 746 | def attack_guessing_entropy_evaluation_cases(self): 747 | # Test extreme evaluation cases 748 | # """ 749 | initial_states = [ 750 | # 1 byte controlled by attacker 751 | [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 752 | 753 | # 16 bytes controlled by attacker 754 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 755 | ] 756 | # """ 757 | 758 | # All 25 evaluation cases 759 | """ 760 | initial_states = [ 761 | # 1 byte controlled by attacker 762 | [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 0 763 | 764 | # 2 bytes controlled by attacker 765 | [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 1 766 | 767 | # 3 bytes controlled by attacker 768 | [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 2 769 | 770 | # 4 bytes controlled by attacker 771 | [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 3 772 | [1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 4 773 | 774 | # 5 bytes controlled by attacker 775 | [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 5 776 | [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 6 777 | 778 | # 6 bytes controlled by attacker 779 | [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 7 780 | [1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], # Case 8 781 | 782 | # 7 bytes controlled by attacker 783 | [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Case 9 784 | [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], # Case 10 785 | 786 | # 8 bytes controlled by attacker 787 | [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], # Case 11 788 | [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0], # Case 12 789 | 790 | # 9 bytes controlled by attacker 791 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], # Case 13 792 | [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0], # Case 14 793 | 794 | # 10 bytes controlled by attacker 795 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], # Case 15 796 | [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0], # Case 16 797 | 798 | # 11 bytes controlled by attacker 799 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], # Case 17 800 | [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0], # Case 18 801 | 802 | # 12 bytes controlled by attacker 803 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], # Case 19 804 | [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1], # Case 20 805 | 806 | # 13 bytes controlled by attacker 807 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], # Case 21 808 | 809 | # 14 bytes controlled by attacker 810 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], # Case 22 811 | 812 | # 15 bytes controlled by attacker 813 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # Case 23 814 | 815 | # 16 bytes controlled by attacker 816 | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Case 24 817 | ] 818 | """ 819 | 820 | # Step 1 821 | start_traces = 10 822 | stop_traces = 50 823 | step_traces = 10 824 | experiments = 10 825 | 826 | print('Run for {} evaluation cases; {} experiments for each evaluation case.'.format(len(initial_states), 827 | experiments)) 828 | 829 | evaluation_case = 0 830 | for initial_state in initial_states: 831 | print('Evaluation case {:2}: {}'.format(evaluation_case, initial_state)) 832 | self.attack_guessing_entropy(evaluation_case, initial_state, start_traces, stop_traces, step_traces, 833 | experiments) 834 | evaluation_case += 1 835 | 836 | 837 | def main(): 838 | attacker = Attacker(generate_traces=True, t_tables_implementation=True, debug=False) 839 | attacker.attack_guessing_entropy_evaluation_cases() 840 | 841 | 842 | if "__main__" == __name__: 843 | start_time = time.time() 844 | 845 | main() 846 | 847 | stop_time = time.time() 848 | 849 | print('Duration: {}'.format(time.strftime('%H:%M:%S', time.gmtime(stop_time - start_time)))) 850 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------