def test_Rotor_encode_letters_forward_return_letter(): A = Rotor('I', 'a') ret = A.encode_letter('a', return_letter=True) index = ALPHABET.index('a'.upper()) output_letter = A.wiring['forward'][(index + A.offset) % 26] output_index = (ALPHABET.index(output_letter) - A.offset) % 26 assert ret == ALPHABET[output_index] assert A.encode_letter('a', printit=True)
def test_Rotor_encode_letters_forward_nothing(): A = Rotor('I', 'a') ret = A.encode_letter('a') index = ALPHABET.index('a'.upper()) output_letter = A.wiring['forward'][(index + A.offset) % 26] output_index = (ALPHABET.index(output_letter) - A.offset) % 26 assert ret == output_index
def test_Rotor_encode_letters_forward_next(): C = Rotor('III', 'a') B = Rotor('II', 'a') A = Rotor('I', 'a') index = ALPHABET.index('a'.upper()) A.next_rotor = B B.prev_rotor = A B.next_rotor = C ret = B.encode_letter('a', forward=True) output_letter = B.wiring['forward'][(index + B.offset) % 26] output_index = (ALPHABET.index(output_letter) - B.offset) % 26 assert ret == B.next_rotor.encode_letter(output_index, True)
def encode_decode_letter(self, letter): """ Takes a letter as input, steps rotors accordingly, and returns letter output. Because Enigma is symmetrical, this works the same whether you encode or decode. """ # Make sure the letter is in a-zA-Z. if bool(re.compile(r'[^a-zA-Z ]').search(letter)): return 'Please provide a letter in a-zA-Z.' # First, go through plugboard. if letter in self.plugboard.swaps: letter = self.plugboard.swaps[letter.upper()] # Next, step the rotors. self.r_rotor.step() # Send the letter through the rotors to the reflector. # Get the index of the letter that emerges from the rotor. left_pass = self.r_rotor.encode_letter(ALPHABET.index(letter.upper())) # Must match letter INDEX, not letter name to reflector as before. refl_output = self.reflector.wiring[ALPHABET[(left_pass)%26]] # Send the reflected letter back through the rotors. final_letter = ALPHABET[self.l_rotor.encode_letter( ALPHABET.index(refl_output), forward=False)] if final_letter in self.plugboard.swaps: return self.plugboard.swaps[final_letter] else: return final_letter