wikipedia https en wikipedia orgwikienigmamachine video explanation https youtu beqwqvmqfob2e also check out numberphile s and computerphile s videos on this topic this module contains function enigma which emulates the famous enigma machine from wwii module includes enigma function showcase of function usage 9 randomly generated rotors reflector aka static rotor original alphabet trapincho used alphabet from string asciiuppercase default selection rotors reflector extra rotors checks if the values can be used for the enigma function validator1 1 1 rotor1 rotor2 rotor3 poland 1 1 1 egzwvonahdclfqmsipjbyukxtr fobhmdkexqnraulpgsjvtyiczw zjxesiuqlhavrmdoygtnfwpbkc p o o p l a a l n d d n param rotpos rotorpositon param rotsel rotorselection param pb plugb validated and transformed return rotpos rotsel pb checks if there are 3 unique rotors checks if rotor positions are valid validates string and returns dict https en wikipedia orgwikienigmamachineplugboard plugboard pictures p i i p c t t c u r r u e s s e plugboard poland p o o p l a a l n d d n in the code pb stands for plugboard pairs can be separated by spaces param pbstring string containing plugboard setting for the enigma machine return dictionary containing converted pairs tests the input string if it a is type string b has even length so pairs can be made checks if all characters are unique created the dictionary the only difference with realworld enigma is that i allowed string input all characters are converted to uppercase nonletter symbol are ignored how it works for every letter in the message input letter goes into the plugboard if it is connected to another one switch it letter goes through 3 rotors each rotor can be represented as 2 sets of symbol where one is shuffled each symbol from the first set has corresponding symbol in the second set and vice versa example abcdefghijklmnopqrstuvwxyz e g fd and df vklepdbgrnwtfcjohqamuzyixs symbol then goes through reflector static rotor there it is switched with paired symbol the reflector can be represented as2 sets each with half of the alphanet there are usually 10 pairs of letters example abcdefghijklm e g e is paired to x zyxwvutsrqpon so when e goes in x goes out and vice versa letter then goes through the rotors again if the letter is connected to plugboard it is switched return the letter enigma hello world 1 2 1 plugb pictures koryh juhhi enigma koryh juhhi 1 2 1 plugb pictures hello world enigma hello world 1 1 1 plugb pictures fpncz qwobu enigma fpncz qwobu 1 1 1 plugb pictures hello world param text input message param rotorposition tuple with 3 values in range 1 26 param rotorselection tuple with 3 rotors param plugb string containing plugboard configuration default return endecrypted string encryptiondecryption process 1st plugboard rotor ra rotor rb rotor rc reflector this is the reason you don t need another machine to decipher 2nd rotors 2nd plugboard movesresets rotor positions else pass error could be also raised raise valueerror invalid symbol reprsymbol used alphabet from string ascii_uppercase default selection rotors reflector extra rotors checks if the values can be used for the enigma function _validator 1 1 1 rotor1 rotor2 rotor3 poland 1 1 1 egzwvonahdclfqmsipjbyukxtr fobhmdkexqnraulpgsjvtyiczw zjxesiuqlhavrmdoygtnfwpbkc p o o p l a a l n d d n param rotpos rotor_positon param rotsel rotor_selection param pb plugb validated and transformed return rotpos rotsel pb checks if there are 3 unique rotors checks if rotor positions are valid validates string and returns dict https en wikipedia org wiki enigma_machine plugboard _plugboard pictures p i i p c t t c u r r u e s s e _plugboard poland p o o p l a a l n d d n in the code pb stands for plugboard pairs can be separated by spaces param pbstring string containing plugboard setting for the enigma machine return dictionary containing converted pairs tests the input string if it a is type string b has even length so pairs can be made checks if all characters are unique created the dictionary the only difference with real world enigma is that i allowed string input all characters are converted to uppercase non letter symbol are ignored how it works for every letter in the message input letter goes into the plugboard if it is connected to another one switch it letter goes through 3 rotors each rotor can be represented as 2 sets of symbol where one is shuffled each symbol from the first set has corresponding symbol in the second set and vice versa example abcdefghijklmnopqrstuvwxyz e g f d and d f vklepdbgrnwtfcjohqamuzyixs symbol then goes through reflector static rotor there it is switched with paired symbol the reflector can be represented as2 sets each with half of the alphanet there are usually 10 pairs of letters example abcdefghijklm e g e is paired to x zyxwvutsrqpon so when e goes in x goes out and vice versa letter then goes through the rotors again if the letter is connected to plugboard it is switched return the letter enigma hello world 1 2 1 plugb pictures koryh juhhi enigma koryh juhhi 1 2 1 plugb pictures hello world enigma hello world 1 1 1 plugb pictures fpncz qwobu enigma fpncz qwobu 1 1 1 plugb pictures hello world param text input message param rotor_position tuple with 3 values in range 1 26 param rotor_selection tuple with 3 rotors param plugb string containing plugboard configuration default return en decrypted string encryption decryption process 1st plugboard rotor ra rotor rb rotor rc reflector this is the reason you don t need another machine to decipher 2nd rotors 2nd plugboard moves resets rotor positions else pass error could be also raised raise valueerror invalid symbol repr symbol
from __future__ import annotations

RotorPositionT = tuple[int, int, int]
RotorSelectionT = tuple[str, str, str]


abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"

reflector = {
    "A": "N",
    "N": "A",
    "B": "O",
    "O": "B",
    "C": "P",
    "P": "C",
    "D": "Q",
    "Q": "D",
    "E": "R",
    "R": "E",
    "F": "S",
    "S": "F",
    "G": "T",
    "T": "G",
    "H": "U",
    "U": "H",
    "I": "V",
    "V": "I",
    "J": "W",
    "W": "J",
    "K": "X",
    "X": "K",
    "L": "Y",
    "Y": "L",
    "M": "Z",
    "Z": "M",
}


rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA"
rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM"
rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN"
rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE"
rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN"
rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS"


def _validator(
    rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str
) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]:
    
    

    if (unique_rotsel := len(set(rotsel))) < 3:
        msg = f"Please use 3 unique rotors (not {unique_rotsel})"
        raise Exception(msg)

    
    rotorpos1, rotorpos2, rotorpos3 = rotpos
    if not 0 < rotorpos1 <= len(abc):
        msg = f"First rotor position is not within range of 1..26 ({rotorpos1}"
        raise ValueError(msg)
    if not 0 < rotorpos2 <= len(abc):
        msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})"
        raise ValueError(msg)
    if not 0 < rotorpos3 <= len(abc):
        msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})"
        raise ValueError(msg)

    
    pbdict = _plugboard(pb)

    return rotpos, rotsel, pbdict


def _plugboard(pbstring: str) -> dict[str, str]:
    
    if not isinstance(pbstring, str):
        msg = f"Plugboard setting isn't type string ({type(pbstring)})"
        raise TypeError(msg)
    elif len(pbstring) % 2 != 0:
        msg = f"Odd number of symbols ({len(pbstring)})"
        raise Exception(msg)
    elif pbstring == "":
        return {}

    pbstring.replace(" ", "")
    
    tmppbl = set()
    for i in pbstring:
        if i not in abc:
            msg = f"'{i}' not in list of symbols"
            raise Exception(msg)
        elif i in tmppbl:
            msg = f"Duplicate symbol ({i})"
            raise Exception(msg)
        else:
            tmppbl.add(i)
    del tmppbl

    
    pb = {}
    for j in range(0, len(pbstring) - 1, 2):
        pb[pbstring[j]] = pbstring[j + 1]
        pb[pbstring[j + 1]] = pbstring[j]

    return pb


def enigma(
    text: str,
    rotor_position: RotorPositionT,
    rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3),
    plugb: str = "",
) -> str:
    

    text = text.upper()
    rotor_position, rotor_selection, plugboard = _validator(
        rotor_position, rotor_selection, plugb.upper()
    )

    rotorpos1, rotorpos2, rotorpos3 = rotor_position
    rotor1, rotor2, rotor3 = rotor_selection
    rotorpos1 -= 1
    rotorpos2 -= 1
    rotorpos3 -= 1

    result = []

    
    for symbol in text:
        if symbol in abc:
            
            if symbol in plugboard:
                symbol = plugboard[symbol]

            
            index = abc.index(symbol) + rotorpos1
            symbol = rotor1[index % len(abc)]

            
            index = abc.index(symbol) + rotorpos2
            symbol = rotor2[index % len(abc)]

            
            index = abc.index(symbol) + rotorpos3
            symbol = rotor3[index % len(abc)]


            symbol = reflector[symbol]

            
            symbol = abc[rotor3.index(symbol) - rotorpos3]
            symbol = abc[rotor2.index(symbol) - rotorpos2]
            symbol = abc[rotor1.index(symbol) - rotorpos1]

            
            if symbol in plugboard:
                symbol = plugboard[symbol]

            
            rotorpos1 += 1
            if rotorpos1 >= len(abc):
                rotorpos1 = 0
                rotorpos2 += 1
            if rotorpos2 >= len(abc):
                rotorpos2 = 0
                rotorpos3 += 1
            if rotorpos3 >= len(abc):
                rotorpos3 = 0

        result.append(symbol)

    return "".join(result)


if __name__ == "__main__":
    message = "This is my Python script that emulates the Enigma machine from WWII."
    rotor_pos = (1, 1, 1)
    pb = "pictures"
    rotor_sel = (rotor2, rotor4, rotor8)
    en = enigma(message, rotor_pos, rotor_sel, pb)

    print("Encrypted message:", en)
    print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))