[Python] Enigma code stops working after 101 characters

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote an enigma code that works fine for the first 100 characters, but after that it just stops encoding correctly. Below is my full code (this time with the plugboard function added). I also commented some lines of code that could be used for debugging, i.e. those lines will show how the letters are changed through different rotors.

    def rotate(string):
    return string[1:] + string[0]
    def rotor_rotations(rotors, alfators, notches):
    rotors[2] = rotate(rotors[2])
    alfators[2] = rotate(alfators[2]) #rotates first rotor every time
    if notches[2] == rotors[2][-1]:
    #print('rotor 2 rotated')
    rotors[1] = rotate(rotors[1]) #rotates second rotor if first rotor is at notch position
    alfators[1] = rotate(alfators[1])
    if notches[1] == rotors[1][-1]: #rotates if second rotor is at notch position
    rotors[0] = rotate(rotors[0])
    alfators[0] = rotate(alfators[0])
    return rotors, alfators
    def rotor(text, rotors, alfators, ukw, notches):
    alfabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    retext = ''
    for letter in text:
    printtext = letter
    rotors, alfators = rotor_rotations(rotors, alfators, notches) #rotate rotors first
    index = alfabet.index(letter)
    for i in range(2, -1, -1): #go through rotors 1, 2 and 3
    letter = rotors[index]
    # printtext += '⚙' + letter
    index = alfators.index(letter)
    letter = ukw[0][index] #go through the reflector
    #printtext += '⇄' + letter
    index = rotors[0].index(letter)
    for i in range(1, 3): #go through rotors 3, 2, 1
    letter = alfators[index]
    # printtext += '⚙' + letter
    index = rotors.index(letter)
    letter = alfabet[index]
    #printtext += '⚙' + letter
    retext += letter
    #print(printtext)
    return retext, rotors, alfators
    def enigma(text):
    rotors =['EKMFLGDQVZNTOWYHXUSPAIBRCJ', 'AJDKSIRUXBLHWTMCQGZNPYFVOE', 'BDFHJLCPRTXVZNYEIWGAKMUSQO']
    alfators = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']*3
    ukw = ['YRUHQSLDPXNGOKMIEBFZCWVJAT']
    notches = ['X', 'S', 'M']
    plugboard_settings = {}
    text = text.split(' ')
    encrypted_text = ''
    for piece in text:
    first = plugboard(piece, plugboard_settings)
    second, rotors, alfators = rotor(first, rotors, alfators, ukw, notches)
    encrypted_text += plugboard(second, plugboard_settings) + ' '
    return encrypted_text

    def plugboard(piece, settings):
    # No plugboard functionality implemented yet
    return piece

    Continue reading...

Compartilhe esta Página