Beispiel #1
0
 def stopFrame(cls):
     reflector = Reflector()
     reflector.rms = CodingTable.rms[CodingTable.kStopFrameIndex]
     fd = cls(reflector=reflector, pitch=0, repeat=False)
     fd.decodeFrame = False
     fd.stopFrame = True
     return fd
 def __init__(self, rotors, keys, reflector):
     self.plug = Plugboard()
     self.static = StaticRotor()
     self.left = Rotor(rotors[0], keys[0])
     self.middle = Rotor(rotors[1], keys[1])
     self.right = Rotor(rotors[2], keys[2])
     self.reflector = Reflector(reflector)
     self.rotors = rotors
     self.initialKeys = keys
Beispiel #3
0
    def __init__(self,
                 walzenlage=['I', 'II', 'III'],
                 ringstellung=['A', 'A', 'A'],
                 grundstellung=['A', 'A', 'A'],
                 umkehrwalze='A',
                 verbose=True):
        # validate machine parameters
        self.__validate(walzenlage, ringstellung, grundstellung, umkehrwalze)

        # set variables for machine usage
        self._plugboard = Plugboard(verbose)
        self._rotors = Rotors(walzenlage, ringstellung, grundstellung, verbose)
        self._reflector = Reflector(umkehrwalze, verbose)
Beispiel #4
0
 def __init__(self, settings=[0], steckers=[], reflector='A', verbose=False):
     self.verbose = verbose
     self.reflector = Reflector(reflector)
     self.rotors = []
     self.steckers = []
     for i,setting in enumerate(settings):
         self.rotors.append(Rotor(i, setting))
     for stecker in steckers:
         self.steckers.append(Stecker(stecker))
class EnigmaController:
    def __init__(self, rotors, keys, reflector):
        self.plug = Plugboard()
        self.static = StaticRotor()
        self.left = Rotor(rotors[0], keys[0])
        self.middle = Rotor(rotors[1], keys[1])
        self.right = Rotor(rotors[2], keys[2])
        self.reflector = Reflector(reflector)
        self.rotors = rotors
        self.initialKeys = keys

    def cipher(self, plainLetter):
        # Movimientos en notch/al iniciar cifrado
        if self.middle.isNotch():
            self.middle.step()
            self.left.step()
        if self.right.isNotch():
            if not self.middle.isNotch():
                self.middle.step()
        self.right.step()
        # Si se quiere usar el plugboard descomentar las siguientes lineas
        cipherPlug = self.plug.cipher(plainLetter)
        cipherStatic = self.static.cipher(cipherPlug)
        cipherRightRotor = self.right.cipherLeft(cipherStatic)
        cipherMiddle = self.middle.cipherLeft(cipherRightRotor)
        cipherLeft = self.left.cipherLeft(cipherMiddle)
        cipherReflector = self.reflector.cipher(cipherLeft)
        cipherLeft = self.left.cipherRight(cipherReflector)
        cipherMiddle = self.middle.cipherRight(cipherLeft)
        cipherRight = self.right.cipherRight(cipherMiddle)
        return cipherRight

    def getKey(self):
        return [self.left.getKey(), self.middle.getKey(), self.right.getKey()]

    def getRotors(self):
        return [
            self.left.getRotor(),
            self.middle.getRotor(),
            self.right.getRotor()
        ]

    def setRotorsAndKeys(self, rotors, keys):
        self.left = Rotor(rotors[0], keys[0])
        self.middle = Rotor(rotors[1], keys[1])
        self.right = Rotor(rotors[2], keys[2])
        self.initialKeys = keys

    def setKeys(self, keys):
        self.setRotorsAndKeys(self.rotors, keys)

    def resetKeys(self):
        self.setKeys(self.initialKeys)
Beispiel #6
0
class Enigma:

    def __init__(self, rotorSettings, plugBoardWiring):
        self.rotorBox1 = RotorBox(rotorSettings)
        self.reflector1 = Reflector("B")
        self.plugboard1 = Plugboard(plugBoardWiring)

    def encrypt(self, inputValue):
        inputValue = self.plugboard1.plugThrough(inputValue)
        self.beforeReflection = self.rotorBox1.getRotorBoxOutput(inputValue)
        self.afterReflection = self.reflector1.reflect(self.beforeReflection)
        return self.plugboard1.plugThrough(self.rotorBox1.getInverseRotorBoxOutput(self.afterReflection))
Beispiel #7
0
 def __init__(self):
     self._rotorList = [
         Rotor(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ',
               notch="Q",
               name="I",
               model="Enigma 1",
               date="1930"),
         Rotor(wiring="AJDKSIRUXBLHWTMCQGZNPYFVOE",
               notch="E",
               name="II",
               model="Enigma 1",
               date="1930"),
         Rotor(wiring="BDFHJLCPRTXVZNYEIWGAKMUSQO",
               notch="V",
               name="III",
               model="Enigma 1",
               date="1930"),
         Rotor(wiring="ESOVPZJAYQUIRHXLNFTGKDCMWB",
               notch="J",
               name="IV",
               model="M3 Army",
               date="December 1938"),
         Rotor(wiring="VZBRGITYUPSDNHLXAWMJQOFECK",
               notch="Z",
               name="V",
               model="M3 Army",
               date="December 1938")
     ]
     self._reflectorList = [
         Reflector(wiring="EJMZALYXVBWFCRQUONTSPIKHGD", name="Reflector A"),
         Reflector(wiring="YRUHQSLDPXNGOKMIEBFZCWVJAT", name="Reflector B"),
         Reflector(wiring="FVPJIAOYEDRZXWGCTKUQSBNMHL", name="Reflector C")
     ]
     self._rotors = [
         self._rotorList[0], self._rotorList[1], self._rotorList[2],
         self._reflectorList[1]
     ]
Beispiel #8
0
    def __init__(self, buf):
        self.mainBuffer = buf
        self.pitchTable = None
        self.pitchBuffer = Buffer.copy(buf)

        if settings.preEmphasis:
            PreEmphasizer.processBuffer(buf)

        self.pitchTable = {}
        wrappedPitch = False
        if settings.overridePitch:
            wrappedPitch = settings.pitchValue
        else:
            self.pitchTable = self.pitchTableForBuffer(self.pitchBuffer)

        coefficients = sp.zeros(11)

        segmenter = Segmenter(buf=self.mainBuffer, windowWidth=settings.windowWidth)

        frames = []
        for (cur_buf, i) in segmenter.eachSegment():
            HammingWindow.processBuffer(cur_buf)
            coefficients = cur_buf.getCoefficientsFor()
            reflector = Reflector.translateCoefficients(coefficients, cur_buf.size)

            if wrappedPitch:
                pitch = int(wrappedPitch)
            else:
                pitch = self.pitchTable[i]

            frameData = FrameData(reflector, pitch, repeat=False)

            frames.append(frameData)

        if settings.includeExplicitStopFrame:
            frames.append(FrameData.stopFrame())

        self.frames = frames
Beispiel #9
0
class EnigmaMachine:

    _alphabet = list(string.ascii_uppercase)
    _valid_rotors = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII']
    _valid_reflectors = ['A', 'B']

    # walzenlage: rotor order
    # ringstellung: ring setting
    # grundstellung: ground setting / start position
    # umkehrwalze: reflector
    def __init__(self,
                 walzenlage=['I', 'II', 'III'],
                 ringstellung=['A', 'A', 'A'],
                 grundstellung=['A', 'A', 'A'],
                 umkehrwalze='A',
                 verbose=True):
        # validate machine parameters
        self.__validate(walzenlage, ringstellung, grundstellung, umkehrwalze)

        # set variables for machine usage
        self._plugboard = Plugboard(verbose)
        self._rotors = Rotors(walzenlage, ringstellung, grundstellung, verbose)
        self._reflector = Reflector(umkehrwalze, verbose)

    def __validate(self, walzenlage, ringstellung, grundstellung, umkehrwalze):
        # check parameter types
        assert isinstance(walzenlage, list)
        assert isinstance(ringstellung, list)
        assert isinstance(grundstellung, list)
        assert type(umkehrwalze) is str

        # check parameter lengths
        rotor_count = len(walzenlage)
        ringstellung_count = len(ringstellung)
        grundstellung_count = len(grundstellung)
        assert rotor_count == ringstellung_count == grundstellung_count
        assert len(umkehrwalze) == 1

        # check for invalid array values & types
        for rotor in walzenlage:
            assert type(rotor) is str
            assert rotor.upper() in self._valid_rotors
        for r in ringstellung:
            assert type(r) is str
            assert len(r) == 1
            assert r.upper() in self._alphabet
        for g in grundstellung:
            assert type(g) is str
            assert len(g) == 1
            assert g.upper() in self._alphabet
        assert umkehrwalze.upper() in self._valid_reflectors

    # steckerbrett: plugboard
    def add_plugboard_mapping(self, char1, char2):
        self._plugboard.add_mapping(char1, char2)

    def generate_random_plugboard_mapping(self):
        self._plugboard.generate_random_mappings()
        self.print_plugboard()

    def print_plugboard(self):
        self._plugboard.print()

    def reset_plugboard(self):
        self._plugboard.reset()

    def set_ringstellung(self, rotor_label, pos):
        self._rotors.set_ringstellung(rotor_label, pos)

    def set_grundstellung(self, rotor_label, pos):
        self._rotors.set_grundstellung(rotor_label, pos)

    def process_message(self, message):
        output = ''
        message = message.upper()
        for char in message:

            if char in self._alphabet:
                # rotation occurs first
                self._rotors.rotate()

                char = self._plugboard.input_letter(char)
                char = self._rotors.input_letter(char)
                char = self._reflector.reflect_letter(char)
                char = self._rotors.output_letter(char)
                char = self._plugboard.output_letter(char)

                output = output + char
            else:
                output = output + char

        print()
        print('Original Message: ' + message)
        print('Processed Message: ' + output)
        print()
        return output
Beispiel #10
0
 def __init__(self, rotorSettings, plugBoardWiring):
     self.rotorBox1 = RotorBox(rotorSettings)
     self.reflector1 = Reflector("B")
     self.plugboard1 = Plugboard(plugBoardWiring)
Beispiel #11
0
        val2 = self.rotor2.getOutput(val1)
        val3 = self.rotor1.getOutput(val2)
        val4 = self.reflector.getOutput(val3)
        val5 = self.rotor1.getOutput(val4)
        val6 = self.rotor2.getOutput(val5)
        out = self.rotor3.getOutput(val6)
        print(out)



    def increment(self):
        is_r3_cycle = self.rotor3.incrementRotation()
        if is_r3_cycle:
            is_r3_cycle = False
            is_r2_cycle = self.rotor2incrementRotation()
            if is_r2_cycle:
                is_r2_cycle = False
                self.rotor1.incrementRotation()

r1 = Rotor('EKMFLGDQVZNTOWYHXUSPAIBRCJ')
#r1.setRing('B')
r2 = Rotor('AJDKSIRUXBLHWTMCQGZNPYFVOE')
#r2.setRing('B')
r3 = Rotor('BDFHJLCPRTXVZNYEIWGAKMUSQO')
#r3.setRing('B')
rf = Reflector('YRUHQSLDPXNGOKMIEBFZCWVJAT')
asssembly = RotorAssembly(r1,r2,r3,rf)
asssembly.getOutput('A')


Beispiel #12
0
class Enigma:
    def __init__(self, settings=[0], steckers=[], reflector='A', verbose=False):
        self.verbose = verbose
        self.reflector = Reflector(reflector)
        self.rotors = []
        self.steckers = []
        for i,setting in enumerate(settings):
            self.rotors.append(Rotor(i, setting))
        for stecker in steckers:
            self.steckers.append(Stecker(stecker))

    def print_settings(self):
        for i,ri in enumerate(self.rotors):
            print "%d:\t%d"%(i,ri.setting)

    def print_rotor_positions(self):
        for ri in self.rotors:
            print "%2d "%ri.position,
        print

    def map(self, letter):
        current = letter.upper()
        for si in self.steckers:
            if self.verbose:
                if current != si.map(current):
                    print "%s->%s,"%(current, si.map(current)),
            current = si.map(current)
        for ri in self.rotors:
            if self.verbose: print "%s->%s,"%(current, ri.map(current)),
            current = ri.map(current)
        if self.verbose: print "%s->%s,"%(current, self.reflector.map(current)),
        current = self.reflector.map(current)
        for ri in reversed(self.rotors):
            if self.verbose: print "%s->%s,"%(current, ri.rev_map(current)),
            current = ri.rev_map(current)
        for si in self.steckers:
            if self.verbose:
                if current != si.map(current):
                    print "%s->%s,"%(current, si.map(current)),
            current = si.map(current)
        if self.verbose: print
        return current

    def update_rotor_positions(self):
        self.rotors[0].position += 1
        for i in range(len(self.rotors)):
            if self.rotors[i].position == 26:
                self.rotors[i].position = 0
                if i < len(self.rotors)-1:
                    self.rotors[i+1].position += 1

    def reset_rotors(self):
        for ri in self.rotors:
            ri.position = ri.setting

    def encode(self, secret_message):
        output = ""
        for letter in secret_message:
            if not letter.isalpha():
                continue
            if self.verbose: self.print_rotor_positions()
            output += self.map(letter)
            self.update_rotor_positions()
        return output
Beispiel #13
0
from Enigma import Enigma
from Rotor import Rotor
from Reflector import Reflector
from Plugboard import Plugboard
import string

if __name__ == '__main__':
    map = {1: 5, 2: 4, 3: 6}
    #rotor = Rotor(int_map=string.ascii_uppercase, notch='Q')
    rotor1 = Rotor(let_map="I")
    rotor2 = Rotor(let_map='II')
    rotor3 = Rotor(let_map='III')
    reflector = Reflector(let_map="B")
    plugboard = Plugboard(let_map='empty')
    enigma = Enigma(rotor1, rotor2, rotor3, reflector, plugboard)
    text = input("Podaj tekst do zakodowania:")
    x = enigma.encrypt(text)
    print(x)

    # letter = 'H'
    # x = rotor3.encrypt_letter(letter)
    # print(x)
    # rotor3.move_rotor()
    # x = rotor3.encrypt_letter(letter)
    # print(x)
    # x = reflector.encrypt_letter(letter)
    # print(x)

Beispiel #14
0
def on_click():
    if not check_combo():
        alert(text="You choose some equal rotors, the program will stop now.",
              title="Error!",
              button="OK")
        #window.close()
        cb1.setCurrentIndex(0)
        cb2.setCurrentIndex(1)
        cb3.setCurrentIndex(2)
        #sys.exit(0)
    else:
        # Check what the first given rotor is.
        if str(cb1.currentText()) == "I":
            rotor1 = Rotor(int(textRingOffset1.text()),
                           int(textRingSetting1.text()),
                           "EKMFLGDQVZNTOWYHXUSPAIBRCJ", 17)
        if str(cb1.currentText()) == "II":
            rotor1 = Rotor(int(textRingOffset1.text()),
                           int(textRingSetting1.text()),
                           "AJDKSIRUXBLHWTMCQGZNPYFVOE", 5)
        if str(cb1.currentText()) == "III":
            rotor1 = Rotor(int(textRingOffset1.text()),
                           int(textRingSetting1.text()),
                           "BDFHJLCPRTXVZNYEIWGAKMUSQO", 22)
        if str(cb1.currentText()) == "IV":
            rotor1 = Rotor(int(textRingOffset1.text()),
                           int(textRingSetting1.text()),
                           "ESOVPZJAYQUIRHXLNFTGKDCMWB", 10)
        if str(cb1.currentText()) == "V":
            rotor1 = Rotor(int(textRingOffset1.text()),
                           int(textRingSetting1.text()),
                           "VZBRGITYUPSDNHLXAWMJQOFECK", 26)

        # Check what the second given rotor is.
        if str(cb2.currentText()) == "I":
            rotor2 = Rotor(int(textRingOffset2.text()),
                           int(textRingSetting2.text()),
                           "EKMFLGDQVZNTOWYHXUSPAIBRCJ", 17)
        if str(cb2.currentText()) == "II":
            rotor2 = Rotor(int(textRingOffset2.text()),
                           int(textRingSetting2.text()),
                           "AJDKSIRUXBLHWTMCQGZNPYFVOE", 5)
        if str(cb2.currentText()) == "III":
            rotor2 = Rotor(int(textRingOffset2.text()),
                           int(textRingSetting2.text()),
                           "BDFHJLCPRTXVZNYEIWGAKMUSQO", 22)
        if str(cb2.currentText()) == "IV":
            rotor2 = Rotor(int(textRingOffset2.text()),
                           int(textRingSetting2.text()),
                           "ESOVPZJAYQUIRHXLNFTGKDCMWB", 10)
        if str(cb2.currentText()) == "V":
            rotor2 = Rotor(int(textRingOffset2.text()),
                           int(textRingSetting2.text()),
                           "VZBRGITYUPSDNHLXAWMJQOFECK", 26)

        # Check what the third given rotor is.
        if str(cb3.currentText()) == "I":
            rotor3 = Rotor(int(textRingOffset3.text()),
                           int(textRingSetting3.text()),
                           "EKMFLGDQVZNTOWYHXUSPAIBRCJ", 17)
        if str(cb3.currentText()) == "II":
            rotor3 = Rotor(int(textRingOffset3.text()),
                           int(textRingSetting3.text()),
                           "AJDKSIRUXBLHWTMCQGZNPYFVOE", 5)
        if str(cb3.currentText()) == "III":
            rotor3 = Rotor(int(textRingOffset3.text()),
                           int(textRingSetting3.text()),
                           "BDFHJLCPRTXVZNYEIWGAKMUSQO", 22)
        if str(cb3.currentText()) == "IV":
            rotor3 = Rotor(int(textRingOffset3.text()),
                           int(textRingSetting3.text()),
                           "ESOVPZJAYQUIRHXLNFTGKDCMWB", 10)
        if str(cb3.currentText()) == "V":
            rotor3 = Rotor(int(textRingOffset3.text()),
                           int(textRingSetting3.text()),
                           "VZBRGITYUPSDNHLXAWMJQOFECK", 26)

        # Default Reflector
        reflector = Reflector("YRUHQSLDPXNGOKMIEBFZCWVJAT")

        # The plugboard.
        plug_board = PlugBoard(textPlug.text())

        # Rotors chosen for the Enigma machine.
        rotors = [rotor1, rotor2, rotor3]

        # Creating the Enigma Machine.
        machine = Enigma(rotors, reflector, plug_board)

        # encryption/decryption of the word.
        result = machine.encryptDecrypt(textInput.text())

        alert(text="The encryption/decryption is: " + result,
              title="Answer",
              button="OK")
Beispiel #15
0
from Reflector import Reflector

test = Reflector("BDFHJLCPRTXVZNYEIWGAKMUSQO", 'A')
test.rotate()
print(test.translate('A'))
print(test.reverse('E'))
test.rotate()
print(test.translate('A'))
print(test.reverse('J'))
test.rotate()
print(test.translate('A'))
print(test.reverse('C'))
class Enigma(Substitutor):
    @property
    def offset(self):
        pass

    @property
    def letters_dict(self):
        pass

    """
    All the objects used in enigma.
    """
    plugboard = None

    rotorA = None
    rotorB = None
    rotorC = None
    reflector = Reflector(string_to_dict(R))

    counter = 0

    def __init__(self,
                 _rotorA=None,
                 _rotorB=None,
                 _rotorC=None,
                 _Plugboard=None):
        """
        Initialize the enigma.
        :param _rotorA: Rotor object.
        :param _rotorB: Rotor object.
        :param _rotorC: Rotor object.
        :param _Plugboard: Plugboard object.
        """

        super(Enigma, self)
        # check if the rotors not None - for constructor selection.
        if _rotorA is not None:
            self.rotorA = _rotorA
            self.rotorB = _rotorB
            self.rotorC = _rotorC

            self.plugboard = _Plugboard

        else:
            # If the arguments are None.
            self.initial_enigma()

    def is_value_Exist(self, val, _dictionary):
        """
        Check if the value exist in the dictionary.
        :param val: A-Z letter.
        :param _dictionary: dictionary.
        :return: boolean.
        """
        for key in _dictionary:
            if _dictionary[key] == val:
                return True
        return False

    def legal_input(self, key, action):
        """
        Check if the input is legal.
        :param key: int.
        :param action: string "rotor" or "offset".
        :return:
        """
        if action == "rotor":
            r = range(1, 6)
        if action == "offset":
            r = range(0, 26)

        if isinstance(key, int) is True:
            if key in r:
                return True
        else:
            return False

    # list of the rotors we used.
    global rotors_used
    rotors_used = {1: False, 2: False, 3: False, 4: False, 5: False}

    def Initial_rotor(self):
        """
        Initial rotor object for the enigma.
        :return: Rotor object.
        """
        error = "Illegal input! please follow instructions."
        global rotors_used
        # While the user try to input wrong values.
        while True:
            while True:
                try:
                    rotor_num = input("Enter rotor [1 to 5]: ")
                except NameError:
                    print error
                    continue
                except SyntaxError:
                    print error
                    continue
                if self.legal_input(rotor_num, "rotor") is not True:
                    print error
                    continue
                if rotors_used[rotor_num]:
                    print "You have already used this rotor, please choose another one."
                    continue
                rotors_used[rotor_num] = True
                break
            # Enter ring offset to the rotor.
            while True:
                ring_offset = raw_input(
                    "Enter ring offset of the rotor [A - Z]: ")
                if ring_offset.isalpha():
                    if len(ring_offset) == 1:
                        if ring_offset.islower():
                            ring_offset = ring_offset.upper()
                        ring_offset = self.letter_to_index(ring_offset)
                    else:
                        print error
                        continue
                else:
                    print error
                    continue
                break

            # Enter ring setting to the rotor.
            while True:
                ring_setting = raw_input(
                    "Enter ring setting of the rotor [A - Z]: ")
                if ring_setting.isalpha():
                    if len(ring_setting) == 1:
                        if ring_setting.islower():
                            ring_setting = ring_setting.upper()
                        ring_setting = self.letter_to_index(ring_setting)
                else:
                    print error
                    continue
                break

            return Rotor(string_to_dict(rotors[rotor_num - 1]), rotor_num,
                         ring_offset, ring_setting)

    def Initial_plugboard(self):
        """
        Initial Plugboard object.
        :return: Plugboard object.
        """
        _plugboard = dict()
        error = "Illegal input! please follow instructions\n" \
                "[non alphabetic characters will stop the connecting process].\n"

        stop = False
        while stop is not True:
            while True:
                print "Please enter two letters you want to connect [non alpha to stop]."
                letter_one = raw_input("The first letter: ")
                if letter_one.isalpha() is not True:
                    stop = True
                    break
                letter_two = raw_input("The second letter: ")
                if letter_two.isalpha() is not True:
                    stop = True
                    break
                print
                if len(letter_one) == 1 and len(letter_two) == 1:
                    if letter_one.islower():
                        letter_one = letter_one.upper()
                    if letter_two.islower():
                        letter_two = letter_two.upper()
                    if letter_one in _plugboard or letter_two in _plugboard or self.is_value_Exist(
                            letter_one, _plugboard) or self.is_value_Exist(
                                letter_two, _plugboard):
                        print "Letters already connected. Please try again [non alpha to stop]"
                    else:
                        _plugboard[letter_one] = letter_two
                else:
                    print "Please enter one letter at a time."

        self.plugboard = Plugboard(_plugboard)

    def circular_shifts(self):
        pass

    def forward_translation(self, letter):
        """
        Go through all of the rotors in forward direction.
        :param letter: A-Z char.
        :return: the forward value.
        """
        return self.reflector.forward_translation(
            self.rotorC.forward_translation(
                self.rotorB.forward_translation(
                    self.rotorA.forward_translation(letter))))

    def reverse_translation(self, letter):
        """
        Go through all of the rotors in reverse direction.
        :param letter: A-Z char.
        :return: the reverse value.
        """
        return self.rotorA.reverse_translation(
            self.rotorB.reverse_translation(
                self.rotorC.reverse_translation(letter)))

    def get_input(self):
        """
        Get the plain text from the user.
        :return: return a string ot only A-Z characters.
        """
        plain_text = raw_input(
            'Please enter plain text [non alphabetic characters will be discarded]:\n'
        )
        for letter in plain_text:
            if letter.isalpha() is not True:
                plain_text = plain_text.replace(letter, "")
            elif letter.islower():
                plain_text = plain_text.replace(letter, letter.upper())
        return plain_text

    # Manually create the enigma.
    def initial_enigma(self):
        """
        Initialize the enigma machine.
        :return: the ciphered text.
        """

        # Initialize all three rotors.
        self.rotorA = self.Initial_rotor()
        self.rotorB = self.Initial_rotor()
        self.rotorC = self.Initial_rotor()

        # Give the user an option if to set a plugboard.
        ans = raw_input("Do you want to initialize plugboard? [y or n]")
        if ans == 'y' or ans == 'Y':
            self.Initial_plugboard()
        else:
            self.plugboard = Plugboard(dict())

    def decrypt(self, message=None, show=False):
        """
        decrypt/encrypt a text (same thing).
        :param message: string.
        :param show: show prints or not.
        :return: the encrypted / decrypted text.
        """
        # Print the rotors information.
        if show:
            print "\nSTART MACHINE STATE:"
            print "Right rotor: offset - " + self.index_to_letter(
                self.rotorA.offset
            ) + ".   ring offset - " + self.index_to_letter(
                self.rotorA.ring_setting) + "."
            print "Middle rotor: offset - " + self.index_to_letter(
                self.rotorB.offset
            ) + ".   ring offset - " + self.index_to_letter(
                self.rotorB.ring_setting) + "."
            print "Left rotor: offset - " + self.index_to_letter(
                self.rotorC.offset
            ) + ".   ring offset - " + self.index_to_letter(
                self.rotorC.ring_setting) + ".\n"

            print "Your plugboard is: "
            print self.plugboard.letters_dict
            print

        counter = 0
        plain_text = ""
        cipher_text = ""

        if message is None:
            message = self.get_input()

        # Check the turnover state.
        for letter in message:
            plain_text += letter
            if self.rotorA.is_turnover_notch(
            ) or self.rotorB.is_turnover_notch():
                if self.rotorB.is_turnover_notch():
                    self.rotorC.circular_shifts()
                self.rotorB.circular_shifts()
            self.rotorA.circular_shifts()

            letter = self.plugboard.get_letter(letter)
            cipher_text += self.plugboard.get_letter(
                self.reverse_translation(self.forward_translation(letter)))

            counter = (counter + 1) % 5
            if counter == 0:
                cipher_text += ' '
                plain_text += ' '

        if show:

            # Print the plain and the cipher text.
            print "The plain text:\n" + plain_text
            print "The cipher text:\n" + cipher_text

            # Print the rotors information.
            print "\nFINAL MACHINE STATE:"
            print "Right rotor: offset - " + self.index_to_letter(
                self.rotorA.offset
            ) + ".   ring offset - " + self.index_to_letter(
                self.rotorA.ring_setting) + "."
            print "Middle rotor: offset - " + self.index_to_letter(
                self.rotorB.offset
            ) + ".   ring offset - " + self.index_to_letter(
                self.rotorB.ring_setting) + "."
            print "Left rotor: offset - " + self.index_to_letter(
                self.rotorC.offset
            ) + ".   ring offset - " + self.index_to_letter(
                self.rotorC.ring_setting) + ".\n"

        # Return the text after the machine.
        return cipher_text
Beispiel #17
0
Github Project Repo:
https://github.com/kelvinkellner/Enigma
--------------------------------------------------
"""
# Imports
from Rotor import Rotor
from Reflector import Reflector

# USER VARIABLES

# Init switchboard
switchboard = "" # enter swaps in format 'AB CD EF..." (the real machine performed 10 swaps)

# Init Rotors
rotor_settings = (("I","A","A"),("II","A","A"),("III","Z","A"))
reflector = Reflector("B")

"""
--------------------------------------------------
Inner workings below...
--------------------------------------------------
"""
ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# Receive input message
message = input("Message: ")
encrypted = message.upper()


# Create list of individual switchboard swaps
sb = switchboard.split(" ")
Beispiel #18
0
 def createReflector():
     return Reflector(list("YRUHQSLDPXNGOKMIEBFZCWVJAT"))
Beispiel #19
0
 def frameForDecoding(cls):
     reflector = Reflector()
     fd = cls(reflector=reflector, pitch=0, repeat=False)
     fd.decodeFrame = True
     return fd
Beispiel #20
0
from Enigma import Enigma
from PlugBoard import PlugBoard
from Reflector import Reflector
from Rotor import Rotor
import time

#5 default Rotors
rotor1 = Rotor(6, 1, "EKMFLGDQVZNTOWYHXUSPAIBRCJ", 17)
rotor2 = Rotor(4, 1, "AJDKSIRUXBLHWTMCQGZNPYFVOE", 5)
rotor3 = Rotor(22, 1, "BDFHJLCPRTXVZNYEIWGAKMUSQO", 22)
rotor4 = Rotor(18, 24, "ESOVPZJAYQUIRHXLNFTGKDCMWB", 10)
rotor5 = Rotor(15, 9, "VZBRGITYUPSDNHLXAWMJQOFECK", 26)

#1 default Reflector
reflecor = Reflector("YRUHQSLDPXNGOKMIEBFZCWVJAT")
#default plugBoard configuration
plugboard = PlugBoard("")
#rotors chosen for the Enigma machine
rotors = [rotor1, rotor2, rotor3]
#creating the Enigma Machine
machine = Enigma(rotors, reflecor, plugboard)

#encryption/decryption of the word
start_time = time.time()
res = ""

res = machine.encryptDecrypt("DHTYYZHUCNHUTQ")

print("The encrypted word is:" + res)