def codebreak3_multi(self): """ Searches through every possible combination of rotor, positions, and ring settings to find the settings which produce the crib in the decoded message """ self.name = 'codebreak3_multi' self.attempt = 1 possible_rotors = ['Beta','Gamma','II','IV'] possible_reflectors = ['A','B','C'] # Odd numbers not allowed allowed_digits = set('02468') # Get list of all possible ring settings possible_ring_settings = [i for i in range(1, 26) if set(str(i)) <= allowed_digits] # Iterate over each trio of possible rotor combinations # For each rotor combination... for rotor_combo in itertools.permutations(possible_rotors, 3): # ...and for each reflector... for reflector in possible_reflectors: #...and for each trio of possible ring settings... for ring_combo in itertools.permutations(possible_ring_settings, 3): self.settings['rotors'] = ' '.join(list(rotor_combo)) self.settings['ring_settings'] = ' '.join(list((str(i) for i in ring_combo))) self.settings['reflector'] = reflector # ...run enigma and write output self.enigma = Enigma(self.settings) self.enigma.create_machinery() self.encode_write_output()
def setUp(self): self.key = 'secret_key' self.enigma = Enigma(self.key) self.mock_rotor = [ ('a', 'b'), ('b', 'a'), ]
def codebreak4_plugleads(self): """ Searches through the different possible missing plugleads to find the settings which produce the crib in the decoded message """ self.name = "codebreak4_plugleads" self.attempt = 1 possible_plugs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Amend possible_plugs to remove any already-used plugs for used_plug in self.settings['plugboard_pairs']: if used_plug in possible_plugs: possible_plugs = possible_plugs.replace(used_plug, '') # For each possible remaining plug pair... for plug_pair in itertools.permutations(list(possible_plugs), 2): pairs = self.original_plugboard_pairs i = 0 # For each character in the original string of plug pairs (contains '?') for char in range(len(pairs)): if pairs[char] == '?': # Swap the '?' for one of the remaining possible plugs pairs = pairs[:char] + plug_pair[i] + pairs[char + 1:] i += 1 # Update settings to reflect the new plug pairs list and run through Enigma self.settings['plugboard_pairs'] = pairs self.enigma = Enigma(self.settings) self.enigma.create_machinery() self.encode_write_output()
def test_same_characters_different_sequence(self, r1p: int, r2p: int, r3p: int, repeated_char: str): enigma = Enigma(r1_pos=r1p, r2_pos=r2p, r3_pos=r3p) cipher_text = enigma.encrypt(repeated_char[0] * 26) for test_char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': self.assertNotEqual(cipher_text, test_char * 26) self.assertEqual(repeated_char[0] * 26, enigma.decrypt(cipher_text))
def setUp(self): self.enigma = Enigma(Plugboard('VZBRGITYUPSDNHLXAWMJQOFECK'), Reflector('JPGVOUMFYQBENHZRDKASXLICTW'), Settings("ABC")) self.enigma2 = Enigma(Plugboard('VZBRGITYUPSDNHLXAWMJQOFECK'), Reflector('JPGVOUMFYQBENHZRDKASXLICTW'), Settings("WGF"))
def test_get_offset(): enigma = Enigma() date = '040895' offset = enigma.get_offset(date) expected = '1025' assert expected == offset
def main(): Config.readKeys() enigma = Enigma(Config.setting('key1'), Config.setting('key2'), Config.setting('key3')) print('Enigma... Press Ctrl+D to stop') print('Commands:\n encrypt <message>\n decrypt <message>') try: while True: command = input('> ') try: spaceIndex = command.index(' ') except: print('Invalid command:') print( 'Commands:\n encrypt <message>\n decrypt <message>') continue if command[:spaceIndex] == 'encrypt': print(enigma.encrypt(command[spaceIndex + 1:])) elif command[:spaceIndex] == 'decrypt': print(enigma.decrypt(command[spaceIndex + 1:])) else: print('Invalid command') print( 'Commands:\n encrypt <message>\n decrypt <message>') except (EOFError, KeyboardInterrupt): print() # Put the standard shell prompt on the next line
def test_get_shift(): enigma = Enigma() key = '02715' date = '040895' expected = [3, 27, 73, 20] shift = enigma.get_shift(key, date) assert expected == shift
def test_encrypt_message(): enigma = Enigma() key = '02715' date = '040895' message = 'hello world' encrypted_message = enigma.encrypt_message(message, key, date) assert 'keder ohulw' == encrypted_message
def __init__(self): Enigma.__init__(self) root = Tk() root.title('Enigma Cipher') #root.geometry("200x100") self.make_widgets() self.plain_text.bind("<Key>", self.update) root.mainloop()
def testEnigmaKeyCheck(self, key, rotor_list): assume(len(key) != len(rotor_list)) enigma_type = "M3" if len(rotor_list) == 3 else "M4" machine = Enigma(rotor_list=rotor_list, enigma_type=enigma_type, debug="DEBUG") with self.assertRaises(ValueError): machine.set_key(key)
def __init__(self): self.encrypted_key = [] self.letters = 'abcdefghijklmnopqrstuvwxyz' self.enigma = Enigma(r1='a', r2='a', r3='a', r4='a', r5='a', swap_num=0)
class SimpleMessageCipherTestCase(TestCase): def setUp(self): self.enigma = Enigma() def test_enigma_encrypts_BC_as_JM(self): self.assertEqual('JM', self.enigma.encrypt('BC')) def test_enigma_encrypts_ABC_as_EJM(self): self.assertEqual('EJM', self.enigma.encrypt('ABC'))
class TrivialLeftRotorBothWaysTestCase(TestCase): def setUp(self): self.enigma = Enigma(reflector='YRUHQSLDPXNGOKMIEBFZCWVJAT', rotor='ACDBFZQHIJKLMNOPGRSTUVWXYE') def test_enigma_encrypts_G_as_Z(self): self.assertEqual('Z', self.enigma.encrypt('G')) def test_enigma_encrypts_alphabet_correctly(self): self.assertEqual('YUHRSTZCPXNQOKMILDEFBWVJAG', self.enigma.encrypt('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
def check_enigma(self, plaintext: str, r1p: int = 0, r2p: int = 0, r3p: int = 0): enigma = Enigma(r1_pos=r1p, r2_pos=r2p, r3_pos=r3p) cipher_text = enigma.encrypt(plaintext) self.assertNotEqual(plaintext, cipher_text) self.assertEqual(plaintext, enigma.decrypt(cipher_text))
def test_encryption_with_special_chars(): message = '? : # * }' key = '01020' date = '010203' enigma = Enigma() outcome = enigma.encrypt(message, key, date) expected = {'encryption': '?l:b#l*b}', 'key': '01020', 'date': '010203'} assert expected == outcome
def test_enigma_different_grundstellung(self): self.rotors = ( Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q'), Walzen(wiring='AJDKSIRUXBLHWTMCQGZNPYFVOE', notch='E'), Walzen(wiring='BDFHJLCPRTXVZNYEIWGAKMUSQO', notch='V'), ) machine = Enigma(rotors=self.rotors[::-1], reflector=self.reflector, grundstellung='BBB') self.assertEqual('PGQPW', machine.cipher('AAAAA'))
def test_encrypting_message(): message = 'hello world' key = '02715' date = '040895' enigma = Enigma() outcome = enigma.encrypt(message, key, date) expected = {'encryption': 'keder ohulw', 'key': '02715', 'date': '040895'} assert outcome == expected
class ReflectorUKWBTestCase(TestCase): def setUp(self): self.enigma = Enigma(reflector='YRUHQSLDPXNGOKMIEBFZCWVJAT') def test_enigma_reflects_A_as_Y(self): self.assertEqual('Y', self.enigma.reflect('A')) def test_enigma_reflects_AB_as_YR(self): self.assertEqual('YR', self.enigma.reflect('AB')) def test_enigma_reflects_ABC_as_YRU(self): self.assertEqual('YRU', self.enigma.reflect('ABC'))
class TwoRotorsTestCase(TestCase): def setUp(self): self.enigma = Enigma(reflector='YRUHQSLDPXNGOKMIEBFZCWVJAT', rotor=['ACDBEFGHIJKLMNOPQRSTUVWXYZ', 'ACDBEFGHIJKLMNOPQRSTUVWXYZ']) def test_enigma_encrypts_A_as_Y(self): self.assertEqual('Y', self.enigma.encrypt('A')) def test_enigma_encrypts_AB_as_YH(self): self.assertEqual('YH', self.enigma.encrypt('AB')) def test_enigma_encrypts_alphabet_correctly(self): self.assertEqual('YHRUQSLBPXNGOKMIECFZDWVJAT', self.enigma.encrypt('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
def test_encrypt_decrypt(self, r1p: int, r2p: int, r3p: int, patch_key: str, rotor_selection: list, reflector_selection: int, plaintext: str): enigma = Enigma(r1_pos=r1p, r2_pos=r2p, r3_pos=r3p, patch_key=patch_key, rotor_selection=rotor_selection, reflector_selection=reflector_selection) cipher_text = enigma.encrypt(plaintext) self.assertNotEqual(cipher_text, plaintext) self.assertEqual(plaintext, enigma.decrypt(cipher_text))
def make_machine(): if len(rotor_list) == 3: enigma_type = 'M3' elif len(rotor_list) == 4: enigma_type = 'M4' machine = Enigma(rotor_list=rotor_list, user_reflector=reflector, enigma_type=enigma_type, debug='DEBUG') machine.set_key(key) return machine
def test_shift_letter(): enigma = Enigma() char_1 = 'a' shift_1 = 3 char_2 = 'q' shift_2 = 15 char_3 = 'y' shift_3 = 2 assert enigma.shift_letter(char_1, shift_1) == 'd' assert enigma.shift_letter(char_2, shift_2) == 'e' assert enigma.shift_letter(char_3, shift_3) == ' '
def testEngimaKeyCheck(self, key, rotor_list): assume(len(key) != len(rotor_list)) if len(rotor_list) == 3: enigma_type = 'M3' elif len(rotor_list) == 4: enigma_type = 'M4' machine = Enigma(rotor_list=rotor_list, enigma_type=enigma_type, debug='DEBUG') with self.assertRaises(ValueError): machine.set_key(key)
def codebreak1_reflector(self): """ Searches through all reflectors to find the settings which contain the crib in the decoded message """ self.name = 'codebreak1_reflector' self.attempt = 1 reflectors = ['A','B','C'] for reflector in reflectors: self.settings['reflector'] = reflector self.enigma = Enigma(self.settings) self.enigma.create_machinery() self.encode_write_output()
def detect_region(): region = request.cookies.get('region') if region is None or Enigma.decrypt(request.cookies.get('region')) == '|': reg = Repo.getLocation() region = Enigma.encrypt('|'.join( [reg.get('country_name'), reg.get('country_code')])) @after_this_request def remember_region(response): response.set_cookie('region', region) g.region = region
def make_machine(): if len(rotor_list) == 3: enigma_type = "M3" elif len(rotor_list) == 4: enigma_type = "M4" machine = Enigma( rotor_list=rotor_list, user_reflector=reflector, enigma_type=enigma_type, debug="DEBUG", ) machine.set_key(key) return machine
class SingleLetterCipherTestCase(TestCase): def setUp(self): self.enigma = Enigma() def test_enigma_encrypts_blank_as_blank(self): self.assertEqual('', self.enigma.encrypt('')) def test_enigma_encrypts_A_as_E(self): self.assertEqual('E', self.enigma.encrypt('A')) def test_enigma_encrypts_B_as_J(self): self.assertEqual('J', self.enigma.encrypt('B')) def test_enigma_encrypts_C_as_M(self): self.assertEqual('M', self.enigma.encrypt('C'))
class ReflectorUKWATestCase(TestCase): def setUp(self): self.enigma = Enigma(reflector='EJMZALYXVBWFCRQUONTSPIKHGD') def test_enigma_reflects_A_as_E(self): self.assertEqual('E', self.enigma.reflect('A')) def test_enigma_reflects_AB_as_EJ(self): self.assertEqual('EJ', self.enigma.reflect('AB')) def test_enigma_reflects_ABC_as_EJM(self): self.assertEqual('EJM', self.enigma.reflect('ABC')) def test_enigma_reflects_alphabet_correctly(self): self.assertEqual('EJMZALYXVBWFCRQUONTSPIKHGD', self.enigma.reflect('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
def EnigmaTest1(): enigma = Enigma("CAB", "BAC", "BCA") messages = ['ABC', 'CAB', 'BCA'] for message in messages: enigma.resetRotor() encrypted_m = enigma.encrypt(message) enigma.resetRotor() print(enigma.decrypt(encrypted_m) == message)
def test_default_encode_decode(self): ''' Creates a 20 char long word. Cipher and decipher this message with default parameters. If ciphered and original word different and deciphered and original word is same as deciphered word, test is passed. ''' all_letters = string.ascii_letters + '''0 123/45\t6\n789.,?!:"';''' cipher = Enigma() for _ in range(50): word = random.choices(all_letters, k=20) word = ''.join(word) encoded = cipher.cipher(word) decoded = cipher.decipher(encoded) self.assertNotEqual(encoded, word) self.assertEqual(word, decoded)
def main(): """ Perform the encryption using the machine from file named MACHINE_FILENAME and the message from file named MSG_FILENAME. If MODE is 'e', encrypt; otherwise, decrypt. """ prompt = 'Enter the name of the file that contains the enigma machine: ' enigma_file = open(get_valid_filename(prompt), 'r') enigma_list = [] for line in enigma_file: enigma_list.append(line) enigma_machine = Enigma(enigma_list[0].rstrip(), enigma_list[1].rstrip(), enigma_list[2].rstrip()) enigma_file.close() if not (is_valid_machine(enigma_machine)): print('The supplied file is not a valid enigma machine.') print('Encryption process stopping.') return prompt = 'Enter the name of the file that contains the message: ' msg_file = open(get_valid_filename(prompt), 'r') messages = msg_file.read() messages.rstrip() msg_file.close() mode = get_encryption_mode() if mode == DECODE: # FIXME update these calls to the new functions for msg in decode.process_messages(enigma_machine, messages, mode): print(msg) if mode == ENCODE: print(encode.encipher(messages, enigma_machine))
def setUp(self): self.enigma1_rotorI = Rotor(list("ekmflgdqvzntowyhxuspaibrcj"), turnover_notch=["q"]) self.enigma1_rotorII = Rotor(list("ajdksiruxblhwtmcqgznpyfvoe"), turnover_notch=["e"]) self.enigma1_rotorIII = Rotor(list("bdfhjlcprtxvznyeiwgakmusqo"), turnover_notch=["v"]) self.enigma1_wide_B_reflector = Reflector( list("yruhqsldpxngokmiebfzcwvjat")) self.my_enigma = Enigma( self.enigma1_wide_B_reflector, self.enigma1_rotorI, self.enigma1_rotorII, self.enigma1_rotorIII, double_step=True, )
def codebreak2_positions(self): """ Searches through every possible rotor position to find the settings which produce the crib in the decoded message """ self.name = 'codebreak2_positions' self.attempt = 1 positions = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Iterate over every possible trio of positions for trio in itertools.permutations(list(positions), 3): # Convert trio to a list trio_as_list = [i for i in trio] # Convert list to space-separated string and assign to settings dictionary self.settings['initial_positions'] = ' '.join(trio_as_list) # Run enigma with given settings and write results self.enigma = Enigma(self.settings) self.enigma.create_machinery() self.encode_write_output()
def ci(cipher): permut = PermutationUtils() ringstellung = ["A", "A", "A"] plugboard = permut.build_permutation('') rotors = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V'} notches = {1: 'Q', 2: 'E', 3: 'V', 4: 'J', 5: 'Z'} correct_rotor = [] enigma = Enigma() cont = 0 possible_keys = [] for i in range(5): for j in range(5): for k in range(5): if i != j and i != k and j != k: correct_rotor = [ rotors[i + 1], rotors[j + 1], rotors[k + 1] ] for l1 in range(26): for l2 in range(26): for l3 in range(26): try_rotor_start_pos = [ chr((l1 + 65)), chr((l2 + 65)), chr((l3 + 65)) ] k = Key(correct_rotor, ringstellung, plugboard, try_rotor_start_pos) plain_text = enigma.enigma_enc(cipher, k) frequencies = count_letters(plain_text) ic = 0.0 for freq in frequencies.values(): ic += (freq * (freq - 1)) ic /= ((len(plain_text)) * (len(plain_text) - 1)) if ic > 0.05: possible_keys.append(k) print(correct_rotor, try_rotor_start_pos, ic) possibilities = [] print possible_keys
class TrivialRotorTestCase(TestCase): def setUp(self): self.enigma = Enigma(reflector='YRUHQSLDPXNGOKMIEBFZCWVJAT', rotor='ACDBEFGHIJKLMNOPQRSTUVWXYZ') def test_enigma_encrypts_empty_string_as_empty_string(self): self.assertEqual('', self.enigma.encrypt('')) def test_enigma_encrypts_A_as_Y(self): self.assertEqual('Y', self.enigma.encrypt('A')) def test_enigma_encrypts_AB_as_YU(self): self.assertEqual('YU', self.enigma.encrypt('AB')) def test_enigma_encrypts_ABC_as_YUH(self): self.assertEqual('YUH', self.enigma.encrypt('ABC')) def test_enigma_encrypts_ABCD_as_YUHR(self): self.assertEqual('YUHR', self.enigma.encrypt('ABCD'))
def test_offsets_encode_decode(self): ''' Creates a 20 char long word. Cipher and decipher this message with random offset selections. If ciphered and original word different and deciphered and original word is same as deciphered word, test is passed. ''' all_letters = string.ascii_letters + '''0 123/45\t6\n789.,?!:"';''' for _ in range(50): offsets = random.choices(range(len(all_letters)), k=3) cipher = Enigma(offsets=offsets) word = random.choices(all_letters, k=20) word = ''.join(word) encoded = cipher.cipher(word) decoded = cipher.decipher(encoded) self.assertNotEqual(encoded, word) self.assertEqual(word, decoded)
class TrivialRotorBackwardsTestCase(TestCase): def setUp(self): self.enigma = Enigma(reflector='YRUHQSLDPXNGOKMIEBFZCWVJAT', rotor='ACDBEFGHIJKLMNOPQRSTUVWXYZ') def test_enigma_encrypts_empty_string_as_empty_string(self): self.assertEqual('', self.enigma.encrypt('')) def test_enigma_encrypts_Y_as_A(self): self.assertEqual('A', self.enigma.encrypt('Y')) def test_enigma_encrypts_YR_as_AD(self): self.assertEqual('AD', self.enigma.encrypt('YR')) def test_enigma_encrypts_YRU_as_ADB(self): self.assertEqual('ADB', self.enigma.encrypt('YRU')) def test_enigma_encrypts_YRU_as_ADBC(self): self.assertEqual('ADBC', self.enigma.encrypt('YRUH'))
class EnigmaTestCase(TestCase): def setUp(self): self.enigma = Enigma(reflector='ABCDEFGHIJKLMNOPQRSTUVWXYZ', rotor='ABCDEFGHIJKLMNOPQRSTUVWXYZ') def test_enigma_stores_reflector_as_instance_variable(self): enigma = Enigma(reflector='foo') self.assertEqual('foo', enigma.reflector) @patch('enigma.enigma.Enigma.reflect') def test_enigma_reflector_used_during_encryption_when_present(self, mock_reflect): self.enigma.encrypt('') self.assertEqual(1, mock_reflect.call_count) def test_enigma_stores_rotor_as_list_instance_variable(self): enigma = Enigma(rotor='foo') self.assertEqual(['foo'], enigma.rotor) @patch('enigma.enigma.Enigma.rotate') def test_enigma_rotor_used_during_encryption_when_present(self, mock_rotate): self.enigma.encrypt('') self.assertEqual(2, mock_rotate.call_count)
def ci(cipher): permut = PermutationUtils() ringstellung = ["A", "A", "A"] plugboard = permut.build_permutation('') rotors = {1:'I', 2:'II', 3:'III', 4:'IV', 5:'V'} notches = {1:'Q', 2:'E', 3:'V', 4:'J', 5:'Z'} correct_rotor = [] enigma = Enigma() cont = 0 possible_keys = [] for i in range(5): for j in range(5): for k in range(5): if i != j and i != k and j != k: correct_rotor = [rotors[i+1], rotors[j+1], rotors[k+1]] for l1 in range(26): for l2 in range(26): for l3 in range(26): try_rotor_start_pos = [chr((l1+65)), chr((l2+65)), chr((l3+65))] k = Key(correct_rotor, ringstellung, plugboard, try_rotor_start_pos) plain_text = enigma.enigma_enc(cipher, k) frequencies = count_letters(plain_text) ic = 0.0 for freq in frequencies.values(): ic += (freq*(freq-1)) ic /= ((len(plain_text))*(len(plain_text)-1)) if ic > 0.05: possible_keys.append(k) print(correct_rotor, try_rotor_start_pos, ic) possibilities = [] print possible_keys
def setUp(self): self.enigma = Enigma(reflector='YRUHQSLDPXNGOKMIEBFZCWVJAT', rotor='ACDBEFGHIJKLMNOPQRSTUVWXYZ')
def setUp(self): self.enigma = Enigma()
def setUp(self): self.enigma = Enigma(reflector='YRUHQSLDPXNGOKMIEBFZCWVJAT')
def setUp(self): self.enigma = Enigma(reflector='ABCDEFGHIJKLMNOPQRSTUVWXYZ', rotor='ABCDEFGHIJKLMNOPQRSTUVWXYZ')
def setUp(self): self.enigma = Enigma(reflector='EJMZALYXVBWFCRQUONTSPIKHGD')
class SingleLetterCipherTestCase(TestCase): def setUp(self): self.enigma = Enigma() def test_enigma_encrypts_blank_as_blank(self): self.assertEqual('', self.enigma.encrypt(''))