Example #1
0
class TestRotor(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        pass

    @classmethod
    def tearDownClass(cls):
        pass

    def setUp(self):
        self.rotor = Rotor()

    def tearDown(self):
        pass

    def test_rotor_chars(self):
        self.rotor.set_rotor_chars(["A", "B", "C", "D"])
        self.assertEqual(self.rotor.get_rotor_chars(), ["A", "B", "C", "D"])
        self.assertRaises(RotorCharacterSetCharacterError,
                          self.rotor.set_rotor_chars, ["A", "B", "CC", "D"])
        self.assertRaises(RotorCharacterSetValueError,
                          self.rotor.set_rotor_chars, ["A", 1, "B", "C"])
        self.assertRaises(RotorCharacterSetRepeatedError,
                          self.rotor.set_rotor_chars,
                          ["A", "B", "C", "C", "D", "D"])
        self.assertRaises(RotorCharacterSetTypeError,
                          self.rotor.set_rotor_chars, ("A", "B", "C", "D"))
Example #2
0
def main():
    UPPER_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    testAlphabet = Alphabet(UPPER_STRING)
    permutation1 = Permutation(
        "(AELTPHQXRU) (BKNW) (CMOY) (DFG) (IV) (JZ) (S)", testAlphabet)
    permutation2 = Permutation(
        "(FIXVYOMW) (CDKLHUP) (ESZ) (BJ) (GR) (NT) (A) (Q)", testAlphabet)
    permutation3 = Permutation("(ABDHPEJT) (CFLVMZOYQIRWUKXSG) (N)",
                               testAlphabet)
    permutation4 = Permutation("(AEPLIYWCOXMRFZBSTGJQNH) (DV) (KU)",
                               testAlphabet)
    permutation5 = Permutation(
        "(AE) (BN) (CK) (DQ) (FU) (GY) (HW) (IJ) (LO) (MP) (RX) (SZ) (TV)",
        testAlphabet)

    rotor1 = Rotor("I", permutation1, "TG")
    rotor2 = Rotor("II", permutation2, "A")
    rotor3 = Rotor("III", permutation3, "B")
    rotor4 = Rotor("IV", permutation4, "XO")
    reflector = Reflector("A", permutation5)

    rotors = [reflector, rotor4, rotor3, rotor2, rotor1]

    machine = Machine(testAlphabet, 5, 6, rotors)
    machine.insertRotors(["A", "IV", "III", "II", "I"])
    machine.setRotors("AAAA")

    message = input("What to convert:")
    print(machine.convertMsg(message))
    def __init__(self):
        # Create all rotors used in a M3 Enigma machine
        self.r1 = Rotor(1, [letter for letter in "EKMFLGDQVZNTOWYHXUSPAIBRCJ"],
                        ["Q"])
        self.r2 = Rotor(2, [letter for letter in "AJDKSIRUXBLHWTMCQGZNPYFVOE"],
                        ["E"])
        self.r3 = Rotor(3, [letter for letter in "BDFHJLCPRTXVZNYEIWGAKMUSQO"],
                        ["V"])
        # Store rotors in number mapped dictionary
        self.r_table = {1: self.r1, 2: self.r2, 3: self.r3}

        # plugboard
        self.plugboard = []

        # Initialize rotor sockets
        self.sockets = {1: self.r1, 2: self.r2, 3: self.r3}

        # Create reflectors
        self.reflectors_available = {
            "UKW-B":
            Reflector("UKW-B",
                      [letter for letter in "YRUHQSLDPXNGOKMIEBFZCWVJAT"]),
            "UKW-C":
            Reflector("UKW-C",
                      [letter for letter in "FVPJIAOYEDRZXWGCTKUQSBNMHL"])
        }

        self.reflector = self.reflectors_available["UKW-B"]

        self.alphabet_map = [letter for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
Example #4
0
 def testModBy26(self):
     
     print("Testing mod by 26....")
     rotor = Rotor(1,1,'A')
     number = rotor.modBy26(26)
     assert(number == 0)
     number = rotor.modBy26(-2)
     print(number)
     assert(number == 24)
     print ("modBy26 passed!")
Example #5
0
 def testRotate(self):
     
     print("Testing rotate....")
     rotor = Rotor(1,4,'I')
     alphabets1 = 'KLMNOPQRSTUVWXYZABCDEFGHIJ'
     alphabets2 = 'HIJKLMNOPQRSTUVWXYZABCDEFG'
     rotor.rotate()
     rotor.rotate()
     assert(alphabets1 == rotor.innerContacts)
     assert(alphabets2 == rotor.outerContacts)
     print ("rotate passed!")
Example #6
0
 def testEncode(self):
 
     print("Testing ecode....")
     rotor = Rotor(2,1,'A')
     rotor.rotate()
     alphabets1 = 'BCDEFGHIJKLMNOPQRSTUVWXYZA'
     alphabets2 = 'BCDEFGHIJKLMNOPQRSTUVWXYZA'
     position = rotor.encode(0)
     assert(alphabets1 == rotor.innerContacts)
     assert(alphabets2 == rotor.outerContacts)
     assert(position == 2)
     print("Encode passed")
Example #7
0
class Tests_Rotor(unittest.TestCase):
    def setUp(self):
        self.alph = Rotor("ABCDEF")

    def test_init(self):
        self.assertEqual(self.alph.alphabet, ["A", "B", "C", "D", "E", "F"])

    def test_rotor_encode(self):
        self.assertEqual(
            self.alph.rotor_encode([0], ["F", "E", "D", "C", "B", "A"]), [5])

    def test_rotor_decode(self):
        self.assertEqual(
            self.alph.rotor_decode([0], ["F", "E", "D", "C", "B", "A"]), [5])
Example #8
0
def RotorTest():
    r = Rotor("FABECD")
    print(r.encryptLetter('D') == 'E')
    print(r.decryptLetter('E') == 'D')
    r.click()
    print(r.encryptLetter('D') == 'C')
    print(r.decryptLetter('E') == 'C')
Example #9
0
 def testSetOrientation(self):
     
     print("Testing set orientation....")
     rotor = Rotor(1,4,'I')
     alphabets1 = 'IJKLMNOPQRSTUVWXYZABCDEFGH'
     alphabets2 = 'FGHIJKLMNOPQRSTUVWXYZABCDE'
     assert(alphabets1 == rotor.innerContacts)
     assert(alphabets2 == rotor.outerContacts)
     rotor = Rotor(0,1,'A')
     rotor.setOrientation('I')
     alphabets1 = 'IJKLMNOPQRSTUVWXYZABCDEFGH'
     alphabets2 = 'IJKLMNOPQRSTUVWXYZABCDEFGH'
     assert(alphabets1 == rotor.innerContacts)
     assert(alphabets2 == rotor.outerContacts)
     print ("set orientation passed!")
    def setup_rotors(self, rotor_selection, rotor_settings):
        """[summary]

        Args:
            rotor_selection ([type]): [description]
            rotor_settings ([type]): [description]

        Returns:
            [type]: [description]
        """

        # Setup rotor strings
        rotor_str = []

        for index, obj in enumerate(self.rotor_selection):
            selection_index = rotor_selection[index] - 1
            rotor_wiring = self.rotor_settings_strings[selection_index]
            rotor_str.append(rotor_wiring)

        # Setup ring settings
        ring_pos = []
        for index, obj in enumerate(self.ring_positions):
            ring_pos.append(self.ring_positions[index])

        rotor_list = []

        # Configure rotors and rotor attributes
        for index, obj in enumerate(rotor_selection):
            rotor_list.append(
                Rotor(rotor_str[index], rotor_settings[index],
                      rotor_selection[index], ring_pos[index]))
        return rotor_list
Example #11
0
    def parse_xml_tree(self, root):
        # parse node
        if root.tag == "render_file":
            self.render_filename = root.attrib["filename"]

        if root.tag == "mass_property":
            self.mass = float(root.attrib["mass"])
            self.inertia_tensor = self.convert_str_to_matrix(
                root.attrib["inertia_tensor"], 3, 3)

        if root.tag == "rotor":
            pos = self.convert_str_to_vector(root.attrib["position"], 3)
            dir = self.convert_str_to_vector(root.attrib["direction"], 3)
            clockwise = (root.attrib["clockwise"] == "1")
            torque_coef = float(root.attrib["torque_coef"])
            rotor = Rotor(position_body=pos,
                          direction_body=dir,
                          clockwise=clockwise,
                          torque_coef=torque_coef)
            self.rotors.append(rotor)

        if root.tag == "wing":
            area = float(root.attrib["area"])
            dir = self.convert_str_to_vector(root.attrib["direction"], 3)
            angle0 = math.radians(float(root.attrib["angle0"]))
            wing = Wing(area=area, direction=dir, angle0=angle0)
            self.wing = wing

        # search sub-tree
        for child in root:
            self.parse_xml_tree(child)
Example #12
0
def create_rotor(model, ring_setting=0):
    """Factory function to create and return a rotor of the given model name."""

    if model in ROTORS:
        data = ROTORS[model]
        return Rotor(model, data['wiring'], ring_setting, data['stepping'])

    raise RotorError("Unknown rotor type: %s" % model)
Example #13
0
    def __init__(self):
        # Create all rotors used in a M3 Enigma machine
        self.r1 = Rotor("I",
                        [letter for letter in "EKMFLGDQVZNTOWYHXUSPAIBRCJ"],
                        ["Q"])
        self.r2 = Rotor("II",
                        [letter for letter in "AJDKSIRUXBLHWTMCQGZNPYFVOE"],
                        ["E"])
        self.r3 = Rotor("III",
                        [letter for letter in "BDFHJLCPRTXVZNYEIWGAKMUSQO"],
                        ["V"])
        self.r4 = Rotor("IV",
                        [letter for letter in "ESOVPZJAYQUIRHXLNFTGKDCMWB"],
                        ["J"])
        self.r5 = Rotor("V",
                        [letter for letter in "VZBRGITYUPSDNHLXAWMJQOFECK"],
                        ["Z"])
        # Store rotors in number mapped dictionary
        self.r_table = {
            1: self.r1,
            2: self.r2,
            3: self.r3,
            4: self.r4,
            5: self.r5
        }

        # plugboard
        self.plugboard = []

        # Initialize rotor sockets
        self.sockets = {1: self.r1, 2: self.r2, 3: self.r3}

        # Create reflectors
        self.reflectors_available = {
            "UKW-B":
            Reflector("UKW-B",
                      [letter for letter in "YRUHQSLDPXNGOKMIEBFZCWVJAT"]),
            "UKW-C":
            Reflector("UKW-C",
                      [letter for letter in "FVPJIAOYEDRZXWGCTKUQSBNMHL"])
        }

        self.reflector = self.reflectors_available["UKW-B"]

        self.a = [letter for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
    def __init__(self, *letters):
        # Should return error if len(letters) != rotorNumber
        self.rotors = []
        self.turnNumber = 0
        self.rotorSize = len(letters[0])

        letterList = list(letters)
        for i in range(len(letterList)):
            self.rotors.append(Rotor(letterList[i]))
Example #15
0
def create_reflector(model):
    """Factory function to create and return a reflector of the given model
    name.
    
    """
    if model in REFLECTORS:
        return Rotor(model, wiring=REFLECTORS[model])

    raise RotorError("Unknown reflector type: %s" % model)
Example #16
0
    def __init__(self, map_set, initial_states=None):
        rotor_count = len(map_set)
        if not initial_states:
            initial_states = ['A'] * len(map_set)

        self.rotors = []
        for idx in range(rotor_count):
            r = Rotor(key_order=map_set[idx], start_state='A')
            self.rotors.append(r)
Example #17
0
    def setup(self):

        self.add_subsystem('rotor', Rotor(), \
                           promotes_inputs=['*'], \
                           promotes_outputs=['*'])

        self.add_subsystem('nacelle', NacelleAdder(), \
                           promotes_inputs=['rotor_diameter', 'rotor_speed', 'machine_rating', 'gear_ratio', 'crane', 'shaft_angle', \
                                            'shaft_ratio', 'Np', 'shrink_disc_mass', 'carrier_mass', 'flange_length', 'overhang', 'L_rb', \
                                            'gearbox_cm_x', 'tower_top_diameter', 'hss_length'], \
                           promotes_outputs=['*'])


        self.add_subsystem('hub', HubAdder(), \
                           promotes_inputs=['rotor_diameter', 'blade_number', 'machine_rating', \
                                            'L_rb', 'shaft_angle', ('blade_root_diameter', 'root_chord')], \
                           promotes_outputs=['*'])


        self.add_subsystem('cost', RNACost(), \
                           promotes_inputs=['rotor_diameter', 'blade_number', 'machine_rating'], \
                           promotes_outputs=['*'])

        # connections
        self.connect('rotor_torque', 'nacelle.rotor_torque')
        self.connect('rotor_thrust', 'nacelle.rotor_thrust')
        self.connect('rotor_mass', 'nacelle.rotor_mass')
        self.connect('rotor_moment', ['nacelle.rotor_bending_moment_x'],
                     src_indices=[0])
        self.connect(
            'rotor_moment',
            ['nacelle.rotor_bending_moment_y', 'hub.rotor_bending_moment'],
            src_indices=[1])
        self.connect('rotor_moment',
                     'nacelle.rotor_bending_moment_z',
                     src_indices=[2])
        self.connect('rotor_force', 'nacelle.rotor_force_x', src_indices=[0])
        self.connect('rotor_force', 'nacelle.rotor_force_y', src_indices=[1])
        self.connect('rotor_force', 'nacelle.rotor_force_z', src_indices=[2])

        self.connect('blade_mass', ['hub.blade_mass', 'cost.blade_mass'])
        self.connect('MB1_location', 'hub.MB1_location')
        self.connect('hub_mass', 'cost.hub_mass')
        self.connect('pitch_system_mass', 'cost.pitch_system_mass')
        self.connect('spinner_mass', 'cost.spinner_mass')
        self.connect('low_speed_shaft_mass', 'cost.low_speed_shaft_mass')
        self.connect('main_bearing_mass', 'cost.main_bearing_mass')
        self.connect('gearbox_mass', 'cost.gearbox_mass')
        self.connect('generator_mass', 'cost.generator_mass')
        self.connect('high_speed_side_mass', 'cost.high_speed_side_mass')
        self.connect('vs_electronics_mass', 'cost.vs_electronics_mass')
        self.connect('yaw_system_mass', 'cost.yaw_system_mass')
        self.connect('mainframe_mass', 'cost.mainframe_mass')
        self.connect('electrical_mass', 'cost.electrical_mass')
        self.connect('hvac_mass', 'cost.hvac_mass')
        self.connect('cover_mass', 'cost.cover_mass')
        self.connect('controls_mass', 'cost.controls_mass')
Example #18
0
def testRun():
    rightRotor = Rotor(0, 'tlmvpcbsuofnaqdhweiyrjzxgk')

    ciphertext = encode("my message", leftRotor, rightRotor)
    print(leftRotor.order)
    plaintext = decode(ciphertext, leftRotor, rightRotor)

    print(plaintext[::-1])
    key = ''
    print(ciphertext + ' ' + key.join(rightRotor.order))
Example #19
0
def build_clusters(pc):
      from rotor import Rotor

      def take_z_axis(p):
        return -p[2]

      for i,p in enumerate(sort_by_dist):
        distances.append([i, p[2]])
      distances = np.sort(distances, axis=0)
      rotor = Rotor()
      rotor.fit_rotate(distances)
      elbow_index = rotor.get_elbow_index()
      z_filter = []
      for e in range(elbow_index):
        if e < elbow_index-1 and distances[e][1] != distances[e+1][1]:
          z_filter.append(distances[e][1])

      # not_base = [[p[0],p[1],p[2],np.uint32(p[3])] for p in pc if p[2] not in z_filter]
      not_base = [[p[0],p[1],p[2],np.uint32(p[3])] for p in pc if p[2] in z_filter]
      return not_base
Example #20
0
    def setup(self):

        self.add_subsystem('wrap', RNAWrapper(), \
                           promotes_inputs=['*'], \
                           promotes_outputs=['*'])

        self.add_subsystem('rotor', Rotor(), \
                           promotes_inputs=['*'], \
                           promotes_outputs=['*'])

        self.add_subsystem('nacelle', NacelleAdder(), \
                           promotes_inputs=['rotor_diameter', 'rotor_speed', 'machine_rating', 'gear_ratio', 'crane', 'shaft_angle', \
                                            'shaft_ratio', 'Np', 'shrink_disc_mass', 'carrier_mass', 'flange_length', 'overhang', 'L_rb', \
                                            'gearbox_cm_x', 'tower_top_diameter', 'hss_length'], \
                           promotes_outputs=['*'])


        self.add_subsystem('hub', HubAdder(), \
                           promotes_inputs=['rotor_diameter', 'blade_number', 'machine_rating', \
                                            'L_rb', 'shaft_angle', ('blade_root_diameter', 'root_chord')], \
                           promotes_outputs=['*'])


        self.add_subsystem('cost', RNACost(), \
                           #promotes_inputs=['rotor_diameter', 'blade_number', 'machine_rating'], \
                           promotes_outputs=['*'])

        # connections
        self.connect('rotor_torque', 'nacelle.rotor_torque')
        self.connect('rotor_thrust', 'nacelle.rotor_thrust')
        self.connect('rotor_mass', 'nacelle.rotor_mass')
        self.connect('rotor_moment', ['nacelle.rotor_bending_moment_x'],
                     src_indices=[0])
        self.connect(
            'rotor_moment',
            ['nacelle.rotor_bending_moment_y', 'hub.rotor_bending_moment'],
            src_indices=[1])
        self.connect('rotor_moment',
                     'nacelle.rotor_bending_moment_z',
                     src_indices=[2])
        self.connect('rotor_force', 'nacelle.rotor_force_x', src_indices=[0])
        self.connect('rotor_force', 'nacelle.rotor_force_y', src_indices=[1])
        self.connect('rotor_force', 'nacelle.rotor_force_z', src_indices=[2])

        self.connect('blade_mass', 'hub.blade_mass')
        self.connect('MB1_location', 'hub.MB1_location')

        self.connect('rotor_mass', 'cost.rotor_mass')
        self.connect('hub_system_mass', 'cost.hub_system_mass')
        self.connect('nacelle_mass', 'cost.nacelle_mass')
Example #21
0
def main():
    arguments = len(sys.argv) - 1
    leftRotor = Rotor(0, 'abcdefghijklmnopqrstuvwxyz')
    if (sys.argv[1] == '-e' and arguments >= 2):
        rightRotor = Rotor(0, 'tlmvpcbsuofnaqdhweiyrjzxgk')

        ciphertext = encode(sys.argv[2], leftRotor, rightRotor)
        key = ''
        print(ciphertext + ' ' + key.join(rightRotor.order))
    elif (sys.argv[1] == '-d' and arguments >= 3):
        rightRotor = Rotor(0, sys.argv[3])

        plaintext = decode(sys.argv[2], leftRotor, rightRotor)
        print(plaintext[::-1])
    elif (sys.argv[1] == '--test' and arguments == 1):
        testRun()
    elif (sys.argv[1] == '-h' or sys.argv[1] == '--help'):
        print('There are only three ways to run this program')
        print('\tEncrypt:\t -e <plaintext>')
        print('\tDecrypt:\t -d <ciphertext> <key>')
        print('\tTestConfig:\t -test')
    else:
        print('Try passing --help')
Example #22
0
    def test_if_encryptors_are_valid(self):
        self.assertTrue(
            isinstance(
                TypeX(encryptors=[
                    Stator(wiring='ABCDEFOPQGHIJKLMNRSTXYZUVW',
                           initial_position=3),
                    Rotor(wiring='QWERTYUIOPASDFGHJKLZXCVBNM',
                          initial_position=4,
                          notchings=[0, 5, 12, 16, 25])
                ]), TypeX))

        with self.assertRaises(TypeError):
            TypeX(encryptors='a flamingo wrapped in tinsel')

        # Pass in encryptors that include a non-Encryptor
        with self.assertRaises(TypeError):
            TypeX(encryptors=[
                Stator(wiring='ABCDEFOPQGHIJKLMNRSTXYZUVW',
                       initial_position=3), 'flamingo'
            ])

        # Pass in encryptors that include a Reflector
        with self.assertRaises(TypeError):
            TypeX(encryptors=[
                Stator(wiring='ABCDEFOPQGHIJKLMNRSTXYZUVW',
                       initial_position=3),
                Reflector()
            ])

        # Pass in encryptors that are out of order
        with self.assertRaises(ValueError):
            TypeX(encryptors=[
                Rotor(wiring='QWERTYUIOPASDFGHJKLZXCVBNM',
                      initial_position=4,
                      notchings=[0, 5, 12, 16, 25]),
                Stator(wiring='ABCDEFOPQGHIJKLMNRSTXYZUVW', initial_position=3)
            ])
Example #23
0
def main():
    f = input("Введите имя файла: ")
    try:
        file = open(f, "rb")
    except IndexError:
        print("Wrong file")
        return

    rotors = []
    for _ in range(ROTORS_COUNT):
        rotors.append(Rotor())

    enigma = Enigma(rotors, Reflector())

    print(enigma)

    enc_file_name = "enc_" + f
    dec_file_name = "dec_" + f
    enc_file = open(enc_file_name, "wb")

    print("Start encrypting '{0}' ...".format(f))
    while True:
        buf = file.read(MAX_LEN)
        if (not len(buf)):
            file.close()
            enc_file.close()
            print("Encrypting done. Results saved in file: '{0}'".format(
                enc_file_name))
            break
        else:
            enc_str = enigma.encryptStr(buf)
            enc_file.write(enc_str)

    enc_file = open(enc_file_name, "rb")
    dec_file = open(dec_file_name, "wb")

    enigma.reset()
    print("Start decrypting '{0}' ...".format(enc_file_name))
    while True:
        buf = enc_file.read(MAX_LEN)
        if (not len(buf)):
            enc_file.close()
            dec_file.close()
            print("Decrypting done. Results saved in file: '{0}'".format(
                dec_file_name))
            break
        else:
            dec_str = enigma.encryptStr(buf)
            dec_file.write(dec_str)
Example #24
0
def rm_base(pc):
      from rotor import Rotor

      def take_z_axis(p):
        return p[2]

      distances = []
      sort_by_dist = sorted(pc, key=take_z_axis)
      for i,p in enumerate(sort_by_dist):
        distances.append([i, p[2]])
      distances = np.sort(distances, axis=0)
      rotor = Rotor()
      rotor.fit_rotate(distances)
      elbow_index = rotor.get_elbow_index()
      # z_filter = []
      # for e in range(elbow_index):
      #   if e < elbow_index-1 and distances[e][1] != distances[e+1][1]:
      #     z_filter.append(distances[e][1])
      z_filter = [distances[0][1]]
      print("z_filter: ", z_filter)
      # not_base = [p for p in pc if p[2] not in z_filter]
      # not_base = [[p[0],p[1],p[2],np.uint32(p[3])] for p in pc if p[2] not in z_filter]
      not_base = [[p[0],p[1],p[2],np.uint32(p[3])] for p in pc if p[2] in z_filter]
      return not_base
Example #25
0
def main():
    try:
        file = open(sys.argv[1], "rb")
    except IndexError:
        print("Set file as argv[1]")
        return

    rotors = []
    for _ in range(ROTORS_COUNT):
        rotors.append(Rotor())
        
    enigma = Enigma(rotors, Reflector())
    print("!!!!!!!!!")
    print(enigma)
    print("!!!!!!!!!")
    print("!!!!!!!!!")
    print()
    print()

    enc_file_name = "enc_" + sys.argv[1] 
    dec_file_name = "dec_" + sys.argv[1] 
    enc_file = open(enc_file_name, "wb")

    while True:
        # считывается MAX_LEN символов из файла
        buf = file.read(MAX_LEN)
        if(not len(buf)):
            file.close()
            enc_file.close()
            break
        else:
            enc_str = enigma.encryptStr(buf)
            enc_file.write(enc_str)


    enc_file = open(enc_file_name, "rb")    
    dec_file = open(dec_file_name, "wb")
    
    enigma.reset()
    while True:
        buf = enc_file.read(MAX_LEN)
        if(not len(buf)):
            enc_file.close()
            dec_file.close()
            break
        else:
            dec_str = enigma.encryptStr(buf)
            dec_file.write(dec_str)
Example #26
0
    def test_start_position(self):
        r = self.rtr
        self.assertEqual(r.state, 'A')
        self.assertEqual(r.key_order[0], 'W')
        self.assertEqual(r.key_order[3], 'Z')

        r2 = Rotor(key_order=self.mapping)
        self.assertEqual(r2.state_index(), 0)

        r2 = Rotor(key_order=self.mapping, start_state='E')
        self.assertEqual(r2.state_index(), 4)
Example #27
0
 def set_machine(self, characteristic1, characteristic2, characteristic3):
     self.settings.rotate_key()
     self.settings.change_key()
     self.basic1 = self.settings.use_key(0)
     self.basic2 = self.settings.use_key(1)
     self.basic3 = self.settings.use_key(2)
     alpha1 = self.settings.set_characteristic(0, characteristic1)
     alpha2 = self.settings.set_characteristic(1, characteristic2)
     alpha3 = self.settings.set_characteristic(2, characteristic3)
     self.rotor1 = Rotor(alpha1)
     self.rotor2 = Rotor(alpha2)
     self.rotor3 = Rotor(alpha3)
Example #28
0
 def testDecode(self):
 
     print("Testing decode....")
     rotor = Rotor(2,1,'A')
     rotor.rotate()
     alphabets1 = 'BCDEFGHIJKLMNOPQRSTUVWXYZA'
     alphabets2 = 'BCDEFGHIJKLMNOPQRSTUVWXYZA'
     position = rotor.decode(4)
     assert(alphabets1 == rotor.innerContacts)
     assert(alphabets2 == rotor.outerContacts)
     assert(position == 1)
     rotor = Rotor(1,1,'A')
     alphabets1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
     alphabets2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
     position = rotor.decode(18)
     assert(alphabets1 == rotor.innerContacts)
     assert(alphabets2 == rotor.outerContacts)
     assert(position == 4)
     print("Decode passed")
Example #29
0
class Enigma():
    def __init__(self, plugboard, reflektor, settings):
        self.plugboard = plugboard
        self.reflektor = reflektor
        self.rotor1 = None
        self.rotor2 = None
        self.rotor3 = None
        self.settings = settings
        self.basic1 = None
        self.basic2 = None
        self.basic3 = None
        self.encode_text = None

    def set_machine(self, characteristic1, characteristic2, characteristic3):
        self.settings.rotate_key()
        self.settings.change_key()
        self.basic1 = self.settings.use_key(0)
        self.basic2 = self.settings.use_key(1)
        self.basic3 = self.settings.use_key(2)
        alpha1 = self.settings.set_characteristic(0, characteristic1)
        alpha2 = self.settings.set_characteristic(1, characteristic2)
        alpha3 = self.settings.set_characteristic(2, characteristic3)
        self.rotor1 = Rotor(alpha1)
        self.rotor2 = Rotor(alpha2)
        self.rotor3 = Rotor(alpha3)

    def encode(self, sign):
        code1 = self.plugboard.plugboard_encode(sign)
        code2 = self.rotor1.rotor_encode(code1, self.basic1)
        code3 = self.rotor2.rotor_encode(code2, self.basic2)
        code4 = self.rotor3.rotor_encode(code3, self.basic3)
        code5 = self.reflektor.reflect(code4)
        self.encode_text = code5

    def decode(self):
        decode1 = self.rotor3.rotor_decode(self.encode_text, self.basic3)
        decode2 = self.rotor2.rotor_decode(decode1, self.basic2)
        decode3 = self.rotor1.rotor_decode(decode2, self.basic1)
        decode4 = self.plugboard.plugboard_decode(decode3)
        return decode4
Example #30
0
    def __init__(self, data_folder, config_file, play):
        self.render_filename = None
        self.mass = None
        self.inertia_tensor = None
        self.rotors = []
        self.wing = None

        # initialize constant value
        self.gravity = np.array([0, 0, 9.8])
        self.dt_mean = 0.01
        self.dt_std = 0.005
        self.total_iter = 2000

        # parse xml config file
        self.parse_config_file(data_folder + config_file)

        # construct rendering environment
        if play:
            from mujoco_rendering_env import mujoco_env
            self.render_env = mujoco_env.MujocoEnv(model_path=data_folder +
                                                   self.render_filename)
        else:
            self.render_env = None
        self.render_intervel = int(1.0 / 50.0 / self.dt_mean)

        # self.render_env._get_viewer()

        # noise related
        self.noisy_body = True
        self.noisy_sensor = True
        self.state_noise_std = np.array([
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.005, 0.005, 0.005, 0.0005, 0.0005,
            0.0005
        ])
        self.noisy_rotor = False
        self.noisy_aerodynamics = True
        self.simulate_delay = True
        self.delay = 0.04
        self.delay_mean = 0.04
        self.delay_std = 0.01
        self.noisy_dt = True
        self.constrain_motor_output = True
        self.motor_constrain_clip = 0.4
        self.real_rotors = []
        for i in range(len(self.rotors)):
            self.real_rotors.append(
                Rotor(self.rotors[i].position, self.rotors[i].direction,
                      self.rotors[i].clockwise, self.rotors[i].torque_coef))

        # integral term
        self.I_dt = self.dt_mean
        self.I_error = None

        # mass property
        self.real_mass = self.mass
        self.real_inertia_tensor = self.inertia_tensor.copy()

        # initialize rigid body
        self.rigid_body = rigid_body.RigidBody(
            mass=self.mass, inertia_body=self.inertia_tensor)
        self.state = None

        # train or play
        self.play = play

        # training variables
        self.seed()
        self.iter = None
        self.epoch = 0
        self.timesofar = None
        self.target = np.zeros(4)
        self.state_his = None
        self.I_error = np.zeros(4)

        # construct action space
        self.max_thrust = 7.0
        action_low = np.ones(len(self.rotors)) * -1.0 * self.max_thrust / 2.0
        action_high = np.ones(len(self.rotors)) * self.max_thrust / 2.0
        self.action_space = spaces.Box(action_low,
                                       action_high,
                                       dtype=np.float32)

        # construct observation space
        ob = self.get_observation_vector()
        ob_low = np.ones(len(ob)) * (-np.finfo(np.float32).max)
        ob_high = np.ones(len(ob)) * (np.finfo(np.float32).max)
        self.observation_space = spaces.Box(ob_low, ob_high, dtype=np.float32)
Example #31
0
class M3(EnigmaMachine):
    
    def __init__(self,setting):
        
        self.rotorLeft = Rotor(int(setting[0])-1,1,'A') 
        self.rotorMiddle = Rotor(int(setting[1])-1,1,'A')
        self.rotorRight = Rotor(int(setting[2])-1,1,'A')        
        self.reflector = Reflector(int(setting[3]),1,'A')
    
    def numberOfSettableWheels(self):
        """ returns the number of rotors+reflectors in the machine whose position can be set
            by the operator.  for example for the m3 this will be 3, for the m4 it will be 5.
            this will be the length of the string returned by the set/get indicator methods."""
        return len(self.getCurrentIndicators())
     
    def setIndicators (self,setting):
        """ set the orientation of the rotors (and settable reflectors) to the specified
            characters.  the characters correspond to the rotors (and settable reflector)
            in the same order as the walzenlage string.
            for any valid setting:
            m.getCurrentIndicators(m.setIndicators(setting)).equals(setting)"""
            
        self.rotorLeft.setOrientation(setting[0])
        self.rotorMiddle.setOrientation(setting[1])
        self.rotorRight.setOrientation(setting[2])

    def getCurrentIndicators (self):
        """ refers to the current orientation of the rotors (and settable reflectors)
            ie what are the letters you can currently read thru the windows?
            the output characters should be in the same order as the walzenlage string"""
        indicators = ''
        indicators += self.rotorLeft.getOrientation()
        indicators += self.rotorMiddle.getOrientation()
        indicators += self.rotorRight.getOrientation()
        return indicators
        
    def encipher (self,plaintext):
        ciphertext = ''
        plaintext = plaintext.upper()
        for alphabet in plaintext:
            self.rotateRotors()
            #print(self.getCurrentIndicators())
            #print("Alphabet:",alphabet)
            position = string.ascii_uppercase.index(alphabet)
            position = self.rotorRight.encode(position)
            #print(position)
            position = self.rotorMiddle.encode(position)
            #print(string.ascii_uppercase[position])
            position = self.rotorLeft.encode(position)
            #print(string.ascii_uppercase[position])
            position = self.reflector.reflect(position)
            #print(string.ascii_uppercase[position])
            position = self.rotorLeft.decode(position)
            #print(string.ascii_uppercase[position])
            position = self.rotorMiddle.decode(position)
            #print(string.ascii_uppercase[position])
            position = self.rotorRight.decode(position)
            #print(string.ascii_uppercase[position])
            cipherAlphabet = string.ascii_uppercase[position]
            ciphertext += cipherAlphabet
        return ciphertext

    
    def rotateRotors(self):
        """ rotates the rotors based on conditions"""
        
        if self.rotorRight.getOrientation() == self.rotorRight.getNotch():
            if self.rotorMiddle.getOrientation() == self.rotorMiddle.getNotch():
                self.rotorLeft.rotate()
            self.rotorMiddle.rotate()
        elif self.rotorMiddle.getOrientation() == self.rotorMiddle.getNotch():
            self.rotorMiddle.rotate()
            self.rotorLeft.rotate()
        #elif self.rotorLeft.getOrientation() == self.rotorLeft.getNotch():
            #self.rotorLeft.rotate()
        self.rotorRight.rotate()
Example #32
0
class Enigma(object):
    '''Object to handle Enigma encryption. Based on Enigma Machine'''
    def __init__(self, offset1, offset2, offset3):
        self.rot1 = Rotor(offset1, rotor_num=1)
        self.rot2 = Rotor(offset2, rotor_num=2)
        self.rot3 = Rotor(offset3, rotor_num=3)
        self.reflector = Reflector(ALPHABET)
        self.plugboard = Plugboard(ALPHABET, PLUGBOARD_LIST)

    #TODO: Do this better
    def set_rotors(self, offset1, offset2, offset3):
        '''Set the values of the rotors'''
        self.rot1.offset = offset1
        self.rot2.offset = offset2
        self.rot3.offset = offset3

    #TODO: Implement this correctly
    def increment_rotors(self):
        '''Increment the rotors according to the Enigma algorithm'''
        self.rot1.increment()
        if self.rot1.offset == 3:
            self.rot2.increment()
            if self.rot2.offset == 2:
                self.rot3.increment()

    def encipher(self, msg):
        '''Encipher the message according to the Enigma algorithm'''
        output = ''
        for val in msg:
            val = self.plugboard.encipher(val)

            self.increment_rotors()
            val = self.rot1.encipher(val)
            val = self.rot2.encipher(val)
            val = self.rot3.encipher(val)

            val = self.reflector.encipher(val)

            val = self.rot3.decipher(val)
            val = self.rot2.decipher(val)
            val = self.rot1.decipher(val)

            val = self.plugboard.encipher(val)

            output = output + val
        return output
Example #33
0
 def __init__(self, offset1, offset2, offset3):
     self.rot1 = Rotor(offset1, rotor_num=1)
     self.rot2 = Rotor(offset2, rotor_num=2)
     self.rot3 = Rotor(offset3, rotor_num=3)
     self.reflector = Reflector(ALPHABET)
     self.plugboard = Plugboard(ALPHABET, PLUGBOARD_LIST)
Example #34
0
 def setUp(self):
     self.rotor = Rotor()
Example #35
0
 def __init__(self,setting):
     
     self.rotorLeft = Rotor(int(setting[0])-1,1,'A') 
     self.rotorMiddle = Rotor(int(setting[1])-1,1,'A')
     self.rotorRight = Rotor(int(setting[2])-1,1,'A')        
     self.reflector = Reflector(int(setting[3]),1,'A')
Example #36
0
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.patches import Circle, Arrow

import numpy as np

from particles import Particles
from rotor import Rotor

rotor = Rotor()
particles = Particles(rotor=rotor)

fig = plt.figure()
subplot_shape = (2,4)
ax = plt.subplot2grid(subplot_shape, (0,0), rowspan=2, colspan=3)
ax_cumulative_theta = plt.subplot2grid(subplot_shape, (0,3) )
ax_cumulative_theta.xaxis.set_ticks([])

ax_cumulative_v_theta = plt.subplot2grid(subplot_shape, (1,3) )

plt.tight_layout()

ax_main_objs = []
cumulative_plot = None
cumulative_v_plot = None

def init():
    global ax_main_objs
    global cumulative_plot
    global cumulative_v_plot
Example #37
0
from rotor import Rotor
from plugboard import Plugboard
from machine import EnigmaMachine

# erste Version
r3 = Rotor('my rotor1', 'CEADFB', ring_setting=0)  #, stepping='A')
r2 = Rotor('my rotor2', 'CADFEB', ring_setting=0)  #, stepping='A')
r1 = Rotor('my rotor3', 'ADFBCE', ring_setting=0)  #, stepping='A')

# zweite Version / rotiert
# 1 3 2 <- chaotisch
# 2 3 1 <- weniger chaotisch
r1 = Rotor('my rotor1', 'CEADFB', ring_setting=0)  #, stepping='A')
r3 = Rotor('my rotor2', 'CADFEB', ring_setting=0)  #, stepping='A')
r2 = Rotor('my rotor3', 'ADFBCE', ring_setting=0)  #, stepping='A')

#reflector = Rotor('my reflector', 'FVPJIAOYEDRZXWGCTKUQSBNMHL')
reflector = Rotor('my reflector', 'CFAEDB')

#pb = Plugboard.from_key_sheet('AF CD EB')
pb = Plugboard()

machine = EnigmaMachine([r1, r2, r3], reflector, pb)
#machine = EnigmaMachine([r1], reflector, pb)


def mapper(text):
    mapping = 'ENIGMA'
    new_text = ""
    for s in text:
        new_text += mapping[ord(s) - ord('A')] + " "