def initiate_enigma_simulator(self, list_of_rotors, steckerbrett, reflector):
        '''Here is the main algorythm'''
        try:
            # create object of Enigma class
            enigma = Enigma(list_of_rotors, steckerbrett, reflector)
            processed_text = enigma.encryptingCodec(self.ciphered_text)
            print(f'\nHere is your encrypted message: {processed_text}')

            # Exporting files requires
            # processed text and initial settings
            self.export_txt_menu(processed_text)

            # If user has chosen not to import settings from file
            # Exporting settings inserted by hand is available
            if self.choice_import_settings == 'n':
                self.export_json_menu(enigma.initial_settings)

            # print last message
            print('\nThank you for using my Enigma Machine Simulator')
            '''
            All this exceptions regarding values correctness are raised in enigma_class.py
            '''
        except (InvalidRotorValues,
                InvalidRotorQuantity,
                SteckerbrettRepeatedValues,
                SteckerbrettValueError,
                ReflectorValueIsUndefined) as Message:
            # If incorrect values have been inserted user will be asked to insert them again
            self.initiate_enigma_again(Message)
示例#2
0
def test_decrypt_message():
    list_of_rotors = [5, 18, 24]
    steckerbrett = {'O': 'Z', 'B': 'D', 'W': 'T', 'E': 'L'}
    reflector = 'B'
    text = 'LLQROUVWFPLXYJFOAGEREQVGMCZQ'
    enigma = Enigma(list_of_rotors, steckerbrett, reflector)

    assert enigma.encryptingCodec(text) == 'WARSAWUNIVERSITYOFTECHNOLOGY'
示例#3
0
class EnigmaWindow(EnigmaUi):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.main_operations()
        self.export_button_txt.clicked.connect(self.saveFileTxt)
        self.export_button_json.clicked.connect(self.saveFileJson)

    def main_operations(self):
        '''
        Welcoming text at the start of the program
        '''
        self.debugTextBrowser.setText(
            'Thank you for using my Enigma Machine Simulator.\nTo start:\n\
            > browse and choose file containing text\n\
            > browse and choose file containing settings or leave it blank and insert settings yourself\n\
            > click "Start Machine" button to run the program\n\
            > after certain message is showed up in this window,\n\
               you may export processed text and settings to a file\n')
        '''
        Disable Export buttons until the program is initiated
        '''
        self.export_button_json.setEnabled(False)
        self.export_button_txt.setEnabled(False)
        self.export_line_json.setDisabled(True)
        self.export_line_txt.setDisabled(True)
        '''Disable line_edit where inserted path is shown after browsing a file
        Path insertion can only be done via button'''

        self.browse_line_json.setDisabled(True)
        self.browse_line_txt.setDisabled(True)

        # Set path to inserted files as empty strings
        self.txtBrowseFileName = ""
        self.jsonBrowseFileName = ""
        # GET path to inserted files
        self.browse_button_txt.clicked.connect(self.getTxtFile)
        self.browse_button_json.clicked.connect(self.getJsonFile)
        '''START ENIGMA SIMULATOR'''
        self.start_button.clicked.connect(self.run_program)

    def get_settings_from_boxes(self):
        '''
        Getting values from inserted boxes
        '''
        list_of_rotors = self.get_rotor_values_from_combo_boxes()

        # GET VALUE from STECKERBRETT EditLine
        steckerbrett = self.steckerbrett_values.text()
        # Format Steckerbrett string value into dictionary
        steckerbrett = self.enigma_interface.format_to_dict(steckerbrett)

        # if json was not imported, enable exporting
        self.export_button_json.setEnabled(True)

        # GET VALUE from REFLECTOR combobox
        reflector = self.reflector_combo.currentText()

        return list_of_rotors, steckerbrett, reflector

    def run_program(self):
        '''
        Main program.
        '''
        # Message to print after program processed data
        text_to_print = ""
        variables_collected = False

        # if user imported .json file with settings, other settings that
        # were inserted manually will not be taken into account
        if not self.jsonBrowseFileName:
            try:
                list_of_rotors, steckerbrett, reflector = self.get_settings_from_boxes(
                )
                variables_collected = True
            except (SteckerbrettRepeatedValues,
                    SteckerbrettWrongFormat) as Message:
                self.print_messages(Message)

        # If inserted path to .json file is not empty:
        if self.jsonBrowseFileName:
            text_to_print += 'Due to the settings being imported, settings inserted manually are not considered<br>Exporting settings is disabled<hr>'

            # if json was imported, disable exporting
            self.export_button_json.setEnabled(False)

            try:
                list_of_rotors, steckerbrett, reflector = read_json_file(
                    self.jsonBrowseFileName)
                variables_collected = True
            except FileNotFound as Message:
                self.print_messages(Message)

        if variables_collected:
            # If inserted path to .txt file is not empty:
            try:
                ciphered_text = read_txt_file(self.txtBrowseFileName)

                # get processed text
                self.processed_text = self.process_data(
                    list_of_rotors, steckerbrett, reflector, ciphered_text)

                text_to_print += f'Processed text: <p style="color:#2D2"><b>{self.processed_text}</b></p> If you wish to export processed data, use buttons below<br>'
                self.print_messages(text_to_print)

                # Enable EXPORT txt button
                self.export_button_txt.setEnabled(True)

                # export buttons are located in the __init__
                # because I observed multiple clicks when calling
                # button.click.connect function from here
                # it does not affect buttons being disabled
            except (FileNotFoundError, FileNotFound, WrongNumberOfLines,
                    NoTextToProcess, NoAsciiDetected,
                    SteckerbrettRepeatedValues, SteckerbrettValueError,
                    ReflectorValueIsUndefined, InvalidRotorValues,
                    NoReflectorSelected, InvalidRotorQuantity) as Message:
                self.export_button_txt.setEnabled(False)
                self.export_button_json.setEnabled(False)
                self.print_messages(Message)

    """def observe_if_buttons_are_clicked(self):
        self.export_button_txt.clicked.connect(self.saveFileTxt)
        self.export_button_json.clicked.connect(self.saveFileJson)"""

    def process_data(self, list_of_rotors, steckerbrett, reflector,
                     ciphered_text):
        '''Returns processed data from enigma_class'''
        self.enigma = Enigma(list_of_rotors, steckerbrett, reflector)
        processed_text = self.enigma.encryptingCodec(ciphered_text)
        return processed_text

    '''Get values inserted into combo boxes '''

    def get_rotor_values_from_combo_boxes(self):
        '''Returns list of rotors' values selected from comboboxes'''
        alpha = int(self.alpha_combo.currentText())
        beta = int(self.beta_combo.currentText())
        gamma = int(self.gamma_combo.currentText())
        return [alpha, beta, gamma]

    def print_messages(self, message):
        '''Shows text to user'''
        self.debugTextBrowser.setText(str(message))

    '''
    Browse/Import Button Functions
    '''

    def getTxtFile(self):
        filename = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Open file', '', 'Text file (*.txt)')
        # show message about file
        self.browse_line_txt.setText(filename[0])
        self.txtBrowseFileName = filename[0]

    def getJsonFile(self):
        filename = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Open file', '', 'Json file (*.json)')
        # show message about file
        self.browse_line_json.setText(filename[0])
        self.jsonBrowseFileName = filename[0]

    def saveFileTxt(self):
        filename = QtWidgets.QFileDialog.getSaveFileName(
            self, 'Save File', '', 'Text file (*.txt)')
        # show message about file
        self.export_line_txt.setText(filename[0])
        txtExportFileName = pathlib.PureWindowsPath(
            f'{filename[0]}'
        ).name[:
               -4]  # remove .txt extension, it will be added during file saving
        try:
            if txtExportFileName:
                create_file_txt(txtExportFileName, self.processed_text)
                # show message about file
                self.print_messages(
                    f'\n{txtExportFileName}.txt file saved successfully')
        except (UndefinedFileName, WrongFileName) as Message:
            # show error message about file
            self.print_messages(Message)

    def saveFileJson(self):
        filename = QtWidgets.QFileDialog.getSaveFileName(
            self, 'Save File', '', 'Json file (*.json)')
        self.export_line_json.setText(filename[0])
        jsonExportFileName = pathlib.PureWindowsPath(
            f'{filename[0]}'
        ).name[:
               -5]  # remove .json extension, it will be added during file saving

        try:
            if jsonExportFileName:
                create_file_json(jsonExportFileName,
                                 self.enigma.initial_settings)
                # show message about file
                self.print_messages(
                    f'\n{jsonExportFileName}.json file saved successfully')
        except (UndefinedFileName, WrongFileName) as Message:
            # show error message about file
            self.print_messages(Message)