Skip to content
Also from us: TypologyOnline.com · Free personality tests

Enigma Machine: The Cipher That Changed with Every Keypress

How rotating wired wheels, a reflector, and a plugboard created one of history’s most formidable cipher machines—and how mathematics, engineering, captured documents, and human mistakes brought it down.

Try the Enigma Machine Simulator tool
Educational illustration of an Enigma signal passing through a plugboard, rotating wired rotors, and a reflector
Enigma changed its substitution after every keypress by stepping wired rotors before sending the electrical signal through the machine.

The Enigma machine looks almost ordinary. It has a keyboard, a panel of lettered lamps, and a set of small windows showing the current rotor positions. Press a key and one lamp illuminates; write down that letter, press the next key, and continue until the message has been transformed. Underneath that simple interaction, however, the machine is constantly changing.

Press A once and the lampboard might show B. Press A again and it might show D; press it a third time and it might show Z. The machine has not forgotten what A means. A rotor has moved, changing the electrical route between the keyboard and lampboard. Enigma therefore uses not one substitution alphabet but a procession of alphabets, each created mechanically for one moment and replaced before the next letter.

That made Enigma far more formidable than Caesar, Atbash, or an ordinary substitution cipher. Yet it was not unbreakable. Its rotors, plugboard, and vast number of settings mattered, but so did its mathematical structure, operating procedures, predictable message language, captured key material, and operator mistakes.

Enigma's deepest lesson is that practical security belongs to the complete system: machine, key, procedure, operator, attacker, and everything known about the message.

Enigma Machine at a Glance

Feature Enigma machine
Type Electromechanical rotor cipher
Cipher family Polyalphabetic substitution
Main idea Rotating wired wheels change the substitution after every processed letter
Main components Keyboard, plugboard, entry wheel, rotors, reflector, and lampboard
Standard alphabet A–Z
Typical military configuration Three moving rotors, a fixed reflector, and a plugboard
Naval M4 configuration Three moving rotors, one stationary Greek wheel, and a thin reflector
Complete key Model, reflector, rotor choice and order, ring settings, starting positions, and plugboard pairs
Reference configuration Rotors I–II–III, rings AAA, start AAA, reflector B, no plugboard
Known-answer example HELLOWORLD → ILBDAAMTAZ
Decryption Process the ciphertext with the same settings from the original starting positions
Distinctive property A standard military Enigma never enciphers a letter as itself
Security today Historically important, but completely unsuitable for modern security
Best use Learning rotor machines, permutations, stateful encryption, cryptanalysis, and operational security

Enigma was not one machine with one permanent specification. It was a family developed across commercial, diplomatic, and military contexts. The familiar wartime Enigma I, naval M3, and naval M4 use the same broad electrical idea but differ in their available rotors, reflectors, and mechanical arrangements.

What Is the Enigma Machine?

Enigma is an electromechanical polyalphabetic substitution cipher:

  • Electromechanical: pressing a key closes an electrical circuit while moving mechanical parts determine its route.
  • Substitution: the input letter is replaced by another letter.
  • Polyalphabetic: the substitution does not stay fixed because the rotors move as the message is entered.

An ordinary monoalphabetic substitution might use one permanent mapping:

A -> Q
B -> W
C -> E
D -> R

Every A becomes Q for the whole message. Enigma behaves differently:

at one rotor state       A -> B
after the rotors move    A -> D
after another movement   A -> Z

This changing substitution frustrates ordinary frequency analysis. In a simple substitution, every plaintext E contributes to one ciphertext letter's frequency. Under Enigma, different occurrences of E may become many different letters because each is processed at a different rotor state.

The machine does not generate those alphabets through software or electronic memory. It generates them physically. Enigma transforms a letter at one machine state, then changes the state before processing the next letter.

The Enigma Signal Path

A standard military Enigma signal travels through the following components:

Keyboard
   |
   v
Plugboard
   |
   v
Entry wheel
   |
   v
Right rotor -> Middle rotor -> Left rotor
                                  |
                                  v
                              Reflector
                                  |
                                  v
Left rotor <- Middle rotor <- Right rotor
   |
   v
Entry wheel
   |
   v
Plugboard
   |
   v
Lampboard

The reflector turns the signal around. The return journey passes through each rotor's inverse mapping, allowing the same keyboard and lampboard to serve both enciphering and deciphering.

The plugboard swaps selected pairs before the signal enters the rotor system and swaps them again when it returns. If a cable connects A and V, then A enters the rotor system as V, while V enters as A. The same reciprocal exchange happens on the return path.

Military plugboards could physically connect as many as thirteen disjoint pairs, though ten cables became a common wartime operating convention.

The Machine as a Mathematical Function

Enigma looks mechanical, but its components can be described as permutations: reversible rearrangements of the alphabet.

Let:

  • $P$ be the plugboard permutation;
  • $R_s$ be the forward route through the rotor stack at state $s$;
  • $R_s^{-1}$ be the inverse return route;
  • $U$ be the reflector.

At one fixed rotor state, the complete transformation is:

$$ E_s = P \circ R_s^{-1} \circ U \circ R_s \circ P $$

Read from right to left, the expression says:

  1. Apply the plugboard.
  2. Travel forward through the rotors.
  3. Pass through the reflector.
  4. Return through the inverse rotor path.
  5. Apply the plugboard again.

The plugboard and reflector are reciprocal:

$$ P^{-1} = P $$

$$ U^{-1} = U $$

The complete transformation is therefore reciprocal:

$$ E_s^{-1} = E_s $$

The same machine configuration can encipher and decipher, but only if it begins in exactly the same state. If the sender starts at KCH, the receiver must also start at KCH. Beginning at KCI, or at the sender's ending position, produces nonsense.

Why the Rotors Matter

A rotor has 26 electrical contacts on each face. Internal wires connect the contacts on one side to differently positioned contacts on the other, creating a scrambled alphabet.

Standard rotor I uses this wiring:

Input:  ABCDEFGHIJKLMNOPQRSTUVWXYZ
Output: EKMFLGDQVZNTOWYHXUSPAIBRCJ

In its reference orientation, input A connects to E, B to K, C to M, and so on. Once the rotor turns, those internal wires remain fixed but align with different external letters.

For a rotor at position $p$, ring setting $r$, and fixed wiring permutation $W$, a simplified forward transformation is:

$$ R_{p,r}(x) = W(x + p - r) - p + r \pmod{26} $$

The input is shifted into the rotor's current frame, passed through its scrambled wiring, and shifted back out. The return signal uses the inverse wiring:

$$ R_{p,r}^{-1}(x) $$

A rotor is therefore not merely a Caesar shift. It is a scrambled substitution whose alignment changes as the wheel turns.

Rotor Order Changes Everything

A normal three-rotor Enigma has a left, middle, and right rotor. An operator might write the order:

I–II–III

This means rotor I is installed on the left, II in the middle, and III on the right. The electrical signal enters from the right:

forward: III -> II -> I
return:  I -> II -> III

I–II–III is not equivalent to III–II–I. The two arrangements compose the rotor permutations in different orders:

$$ R_I \circ R_{II} \circ R_{III} \ne R_{III} \circ R_{II} \circ R_I $$

Function composition is generally not commutative. Exchanging two rotors changes the result even when every ring setting and starting position remains the same.

Ring Settings and Starting Positions Are Different

These two parts of an Enigma key are easy to confuse:

Setting What it controls Example
Starting position The letter visible in each rotor window before processing begins KCH
Ring setting The offset between the alphabet ring and the rotor's internal wiring AAA

A starting position of KCH means:

left window    K
middle window  C
right window   H

The ring setting changes which internal contact corresponds to the displayed alphabet position. Two machines may show the same window letters and still produce different output because their ring settings differ.

Rings AAA, start KCH

is not equivalent to:

Rings KCH, start AAA

The first changes the visible rotor positions. The second changes the alignment between the alphabet rings and internal wiring. Both are part of the key.

The Rotors Step Before Enciphering

When a key is pressed, the moving rotors advance before the electrical transformation occurs. The right rotor normally advances on every processed letter. Its turnover notch can cause the middle rotor to move, and the middle rotor can move the left rotor.

The mechanism resembles a counter, but it is not a simple odometer. Enigma has a distinctive behaviour called double-stepping. Near turnover, the middle rotor can advance on two consecutive keypresses: first because the right rotor engages it, then because its own notch allows it to advance again while moving the left rotor.

Correct double-stepping is essential to an accurate simulator. A program that treats the machine as three simple wheels will eventually diverge from a historical Enigma.

Rotor Notches

Rotor Turnover letter
I Q
II E
III V
IV J
V Z
VI Z and M
VII Z and M
VIII Z and M

Naval rotors VI, VII, and VIII have two notches, causing more frequent middle-rotor movement.

The notch does not transform the signal. Wiring determines the substitution, position changes the wiring's alignment, and the notch controls when another rotor moves.

The Reflector

The reflector, or Umkehrwalze, sits beyond the left side of the rotor stack. It connects contacts in fixed reciprocal pairs:

A <-> Y
B <-> R
C <-> U

The precise pairings depend on the selected reflector. This component creates two especially important consequences.

The Same Machine Reverses the Message

At one fixed state, if:

A -> B

then:

B -> A

The sender and receiver therefore use the same machine operation. They do not need separate encryption and decryption circuits.

A Letter Cannot Encipher to Itself

Standard military reflectors have no fixed points. A contact never maps directly back to itself. Because the surrounding rotors and plugboard are reversible permutations, the complete machine inherits that property:

A cannot become A
B cannot become B
C cannot become C

This simplified construction and supported reciprocal operation, but it also created a cryptanalytic weakness. If a guessed plaintext fragment placed any letter over the same ciphertext letter, that alignment could be rejected immediately.

The Plugboard

A typical ten-cable plugboard setting is:

AV BS CG DL FU HZ IN KM OW RX

Each pair represents a reciprocal exchange:

Cable Exchange Cable Exchange
AV A ↔ V HZ H ↔ Z
BS B ↔ S IN I ↔ N
CG C ↔ G KM K ↔ M
DL D ↔ L OW O ↔ W
FU F ↔ U RX R ↔ X

The six unconnected letters pass through unchanged.

For exactly ten disjoint pairs, the number of possible plugboard arrangements is:

$$ \frac{26!}{6! \times 10! \times 2^{10}} = 150{,}738{,}274{,}937{,}250 $$

Twenty letters are selected, divided into ten unordered pairs; neither the direction within a pair nor the order of the pairs matters.

The plugboard added an enormous number of settings, but it was still structured. Its reciprocal relationships could be analysed. Gordon Welchman's diagonal-board improvement to the British Bombe exploited those relationships to reject inconsistent candidates more efficiently.

How Large Was the Enigma Keyspace?

Consider the raw setting count for a common Enigma I arrangement:

  • three ordered rotors selected from five;
  • three ring settings;
  • ten plugboard pairs.

The ordered rotor choices contribute:

$$ 5 \times 4 \times 3 = 60 $$

The three written ring settings contribute:

$$ 26^3 = 17{,}576 $$

Multiplying those by the ten-pair plugboard count gives:

$$ 60 \times 17{,}576 \times 150{,}738{,}274{,}937{,}250 = 158{,}962{,}555{,}217{,}826{,}360{,}000 $$

That is approximately:

$$ 1.59 \times 10^{20} $$

raw configurations before separately counting the three-letter starting windows. Including another factor of $26^3$ gives approximately:

$$ 2.79 \times 10^{24} $$

possible written combinations.

This is a useful illustration of scale, not a complete statement of effective security. Mechanical equivalences, double-stepping, procedure restrictions, repeated daily keys, likely plaintext, captured material, and the machine's reciprocal structure reduced the useful search problem.

A large keyspace helps only when an attacker must treat it as an unstructured collection of independent possibilities. Enigma's possibilities were connected by rules and relationships.

The Complete Key and Operating Rules

To reproduce a three-rotor message, sender and receiver need:

  1. Machine model.
  2. Reflector.
  3. Rotor selection and left-to-right order.
  4. Ring settings.
  5. Starting positions.
  6. Plugboard pairs.

An M4 key additionally needs the Greek-wheel selection, ring setting, and starting position.

Rule Historical machine Educational simulator
Alphabet Processes A–Z Usually accepts ordinary text and decides how to handle non-letters
Case No cryptographic distinction May preserve case for readability
Spaces and punctuation Represented using operating conventions Can be removed, preserved without stepping, or converted to letters such as X
Rotor stepping Only processed letters step the machine Preserved punctuation should not cause a step
Grouping Ciphertext commonly written in fixed blocks Display formatting only; group spaces are not enciphered

One incorrect component is enough to destroy the result. The right rotors with the wrong reflector fail; the correct reflector with one wrong ring setting fails; one missing plugboard cable fails; and a start position one letter away fails from the first character.

A One-Letter Worked Example

Use the standard reference configuration:

Machine     Enigma I
Rotors      I–II–III
Rings       AAA
Start       AAA
Reflector   B
Plugboard   none

Press A. The machine first advances the right rotor:

AAA -> AAB

The documented wiring produces this route:

Stage Letter
Keyboard input A
Plugboard A
Entry wheel A
Rotor III forward at position B C
Rotor II forward D
Rotor I forward F
Reflector B S
Rotor I reverse S
Rotor II reverse E
Rotor III reverse at position B B
Plugboard B
Lampboard output B

Therefore, on the first keypress:

A -> B

Press A again and the right rotor moves to C before the signal travels. With the same configuration:

AAAAA -> BDZGO

The repeated plaintext letter no longer creates a repeated ciphertext letter.

A Full Worked Example: HELLOWORLD

Keep the reference configuration and encipher:

HELLOWORLD
Plain letter Windows before keypress Windows after stepping Cipher letter
H AAA AAB I
E AAB AAC L
L AAC AAD B
L AAD AAE D
O AAE AAF A
W AAF AAG A
O AAG AAH M
R AAH AAI T
L AAI AAJ A
D AAJ AAK Z

The result is:

HELLOWORLD -> ILBDAAMTAZ

The three plaintext Ls become B, D, and A; the two Os become A and M. The ciphertext's consecutive AA came from two different plaintext letters, O and W. Enigma disperses ordinary single-letter frequencies across changing states.

How Enigma Decryption Works

The sender enters:

HELLOWORLD

and obtains:

ILBDAAMTAZ

The receiver configures another machine identically and restores the original starting windows:

AAA

Entering the ciphertext then produces:

HELLOWORLD

The receiver does not begin at the sender's final AAK position. That position is the result of processing the message. Decryption must recreate the same sequence of states, so it starts from the original AAA.

Enigma I, M3, and M4

Model Rotor arrangement Available moving rotors Reflector
Enigma I Three moving rotors I–V Standard reflector
Naval M3 Three moving rotors I–VIII Standard naval-compatible reflector
Naval M4 Stationary Beta or Gamma wheel plus three moving rotors I–VIII for the moving positions Thin reflector

Enigma I

The familiar Army and Luftwaffe model normally selects three different moving rotors from I–V. It is the clearest configuration for learning rotor order, rings, starting windows, plugboard wiring, double-stepping, and reciprocity.

The M3 remains a three-moving-rotor machine but adds naval rotors VI–VIII. Those extra rotors have two notches each, increasing the frequency of turnover.

The M4 adds a stationary Beta or Gamma wheel beside a thin reflector while retaining three ordinary moving rotors:

Plugboard
  -> right -> middle -> left
  -> Greek wheel -> thin reflector
  -> Greek wheel reverse
  -> left reverse -> middle reverse -> right reverse
  -> Plugboard

Although commonly described as a four-rotor machine, only three wheels move during ordinary encipherment. The Greek wheel adds another permutation but remains stationary. The M4 was introduced for sensitive German naval traffic, particularly U-boat communications, and caused a serious interruption in Allied reading until new methods, machinery, and captured material restored access.

From Commercial Machine to Military System

Enigma's history began before the Second World War. Arthur Scherbius patented important rotor-machine ideas from 1918, and commercial Enigma machines appeared during the 1920s. They were marketed for protecting business and diplomatic communication before modified variants became embedded in German military networks.

The early machines were not identical to wartime Enigma. The family included different rotor counts, stepping systems, reflectors, keyboards, and output mechanisms. German military services adopted and modified variants, with the plugboard becoming one of the defining improvements of the familiar Wehrmacht machine.

By 1939, Enigma was not an experimental curiosity. It formed part of an organised communications system with key sheets, network procedures, trained operators, and frequently changing configurations.

The Polish Breakthrough Came First

The history is often compressed into one misleading sentence: Alan Turing cracked Enigma. Turing's contribution was extraordinary, but the cipher was not broken by one person, one machine, or one country.

Before Bletchley Park's wartime work, Polish cryptanalysts Marian Rejewski, Jerzy Różycki, and Henryk Zygalski had already made foundational breakthroughs. They combined mathematics, intelligence material, operating-procedure weaknesses, and mechanical aids to reconstruct and attack German Enigma.

Rejewski's use of permutation theory was especially important. Instead of treating Enigma as an unknowable electrical box, he analysed relationships created by repeated indicator procedures. The Polish team developed:

  • the cyclometer;
  • card catalogues;
  • Zygalski sheets;
  • the Polish bomba kryptologiczna.

In July 1939, shortly before Germany invaded Poland, Polish intelligence shared vital Enigma knowledge and reconstructed machines with British and French representatives.

The more accurate historical sequence is:

Polish mathematical breakthroughs
  -> shared knowledge and reconstructed machines
  -> British and French development
  -> large wartime intelligence organisation
  -> Bombes and specialised methods
  -> continuous adaptation as German systems changed

Enigma cryptanalysis was cumulative, international, and collaborative.

Bletchley Park and the Bombe

At Bletchley Park, separate teams attacked different cipher systems and communications networks. Alan Turing became central to naval Enigma work. Gordon Welchman contributed the diagonal board, while engineer Harold “Doc” Keen and the British Tabulating Machine Company turned cryptanalytic designs into operational Bombes.

The Bombe did not accept arbitrary ciphertext and print a plaintext. Human codebreakers first needed a plausible fragment called a crib, drawn from clues such as:

  • standard message formats;
  • weather reports;
  • routine phrases and military vocabulary;
  • known locations or salutations;
  • earlier procedures;
  • information from other intelligence sources.

The crib was aligned against the ciphertext. Alignments containing self-encryption could be discarded. The surviving letter relationships formed a logical network called a menu, which the Bombe tested across rotor orders and positions.

A Bombe stop was a candidate, not a final answer. Codebreakers still had to check it and recover remaining details such as plugboard pairs or ring settings.

A Simple Crib Example

Suppose context suggests the German word:

WETTER

At one alignment:

Plain:   W E T T E R
Cipher:  Q F Z W R W

No letter meets itself, so the alignment remains possible.

At another:

Plain:   W E T T E R
Cipher:  X E B F O G

Plaintext E sits above ciphertext E. The alignment is impossible because Enigma cannot produce E -> E.

This does not reveal the key, but it eliminates work cheaply. A longer crib creates interconnected constraints. The Bombe systematically searches for rotor states that satisfy those relationships without contradiction.

The attack was not brute force alone. It was structured search guided by machine constraints and probable language.

Captured Material Mattered

Cryptanalysis did not exist in isolation from the physical war. Captured machines, rotors, codebooks, weather keys, short-signal books, and procedure documents could transform a difficult problem.

Material recovered from German naval vessels—including U-110 in May 1941 and later captures important to four-wheel naval traffic—complemented mathematical analysis. A captured key list might provide settings for a limited period; a procedure book could reveal how indicators were constructed; a physical rotor could confirm wiring or stepping.

The attack on Enigma combined:

Technical and analytical Operational and contextual
Mathematics Radio interception
Electrical and mechanical engineering Traffic analysis
Linguistic analysis Espionage and naval action
Specialised search machinery Captured documents
Statistical and logical elimination Operator habits and mistakes

It was not one machine against one mathematician. It was one complete intelligence system attacking another complete communications system.

Why Enigma Was Genuinely Useful

Being broken did not make Enigma foolish or useless. In its historical setting it offered major advantages:

Strength Operational value
Rapid mechanical encryption Operators could transform messages without hand-building substitution tables
Constantly changing substitution Ordinary monoalphabetic frequency patterns were dispersed
Reciprocal operation The same equipment and procedure worked at both ends
Replaceable key components Rotors, rings, starts, reflectors, and plugboard cables could change
Portable construction Machines could operate in command posts, ships, and submarines
Standardised procedures Large networks could coordinate changing configurations
Huge apparent setting count Manual exhaustive search was impractical

Enigma was not weak in the way a Caesar cipher is weak. Breaking it demanded mathematical insight, probable plaintext, procedural knowledge, engineering resources, interception networks, and continued adaptation.

Why Enigma Was Not Unbreakable

Its security failed through the interaction of machine properties and real operations:

Weakness or constraint Cryptanalytic consequence
No letter enciphered to itself Impossible crib alignments could be rejected immediately
Reciprocal transformation Legitimate operation was simple, but the machine imposed exploitable structure
Fixed reciprocal reflector The machine could not realise arbitrary permutations
Pairwise plugboard Added many settings, but also created mathematical relationships
Predictable formats and vocabulary Supplied probable plaintext
Daily or network key reuse Recovering one setting could unlock substantial traffic
Weak indicator procedures Leaked repeated relationships to Polish cryptanalysts
Operator mistakes Repeated starts, memorable patterns, and stereotyped language reduced uncertainty
Captured documents Removed parts of the key or procedure problem
Traffic context Stations, time, frequency, network, and military events constrained interpretation

The central weakness was not one bad wire. Enigma existed in the real world.

How Enigma Was Broken in Practice

A simplified attack workflow looked like this:

  1. Intercept the transmission. Listening stations recorded encrypted Morse traffic and associated metadata.
  2. Identify the network. Different services and networks used different variants, keys, and procedures.
  3. Propose a crib. Cryptanalysts used language, format, timing, and context to guess a plaintext fragment.
  4. Reject impossible alignments. Any position containing A/A, B/B, or another self-match was impossible.
  5. Construct a menu. Plaintext–ciphertext relationships became a connected logical structure.
  6. Configure the Bombe. Operators wired that menu into the machine.
  7. Test rotor possibilities. The Bombe rejected settings that created contradictions.
  8. Investigate stops. A stop was checked rather than accepted blindly.
  9. Recover remaining details. Analysts determined necessary plugboard, ring, or procedure information.
  10. Decrypt more traffic. A recovered daily or network key could unlock related messages.
  11. Translate and assess. Plaintext was compared with other intelligence and distributed under strict controls.

The exact workflow changed across networks and periods. Naval Enigma presented special difficulties; the M4 required further developments, including high-speed US Navy Bombes for four-wheel traffic.

Why Pure Frequency Analysis Is Not Enough

In a monoalphabetic substitution, every plaintext E becomes the same ciphertext letter, so frequencies remain directly connected. Enigma disperses one letter across many outputs:

plaintext E at ten rotor states
  -> Q M A T L X P B N F

Language structure does not disappear completely. Attackers can still use probable words, repeated formats, message lengths, network conventions, known events, operator habits, and machine constraints.

The cryptanalytic question changes from:

Which ciphertext letter probably represents E?

to:

Which likely phrase belongs here, and which machine states are compatible with it?

That is a more contextual and powerful attack.

System Relationship to Enigma
Caesar cipher One fixed shifted alphabet; Enigma changes continually
Monoalphabetic substitution One permanent scrambled alphabet; Enigma uses state-dependent permutations
Vigenère cipher Repeating polyalphabetic shifts; Enigma generates alphabets mechanically over a much longer state cycle
Hebern rotor machine Independent early rotor-machine tradition from a similar period
Typex British rotor machine influenced by the same broad principle
Lorenz SZ German teleprinter system attacked with different methods; not an Enigma variant
Fialka Later Soviet rotor machine with additional design features
One-time pad A fundamentally different system that is secure when its random key is as long as the message and never reused
Modern block cipher Electronic, binary, and formally analysed rather than built from mechanical alphabet wheels

Enigma and Lorenz are often blurred in popular accounts. They were different systems. The Bombe was associated with Enigma; Colossus was developed for parts of the attack on Lorenz traffic.

Where Enigma Appears Today

Enigma no longer protects serious communications. Its modern life is educational, historical, and recreational:

  • cryptography museums and Second World War exhibitions;
  • university courses and programming exercises;
  • escape rooms, puzzle hunts, and strategy games;
  • browser simulators and codebreaking challenges;
  • mechanical replicas and electronic reconstructions.

It remains a powerful teaching object because it makes abstract ideas visible. A learner can watch a wheel move, follow a signal through composed substitutions, see a reflector create reciprocity, and connect one convenient design rule to a cryptanalytic weakness.

Modern cryptography usually happens too quickly and invisibly to follow. Enigma slows the process down: one key, one step, one circuit, one lamp.

A Python Enigma Simulator

The following educational implementation models the central behaviour of a three-moving-rotor Enigma I or M3-style machine. It includes rotors I–VIII, reflectors B and C, ring and start settings, plugboard pairs, pre-key stepping, middle-rotor double-stepping, dual naval notches, reciprocal processing, and optional non-letter preservation.

Python exampleShow code
from dataclasses import dataclass


ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"


ROTOR_SPECS = {
    "I": (
        "EKMFLGDQVZNTOWYHXUSPAIBRCJ",
        "Q",
    ),
    "II": (
        "AJDKSIRUXBLHWTMCQGZNPYFVOE",
        "E",
    ),
    "III": (
        "BDFHJLCPRTXVZNYEIWGAKMUSQO",
        "V",
    ),
    "IV": (
        "ESOVPZJAYQUIRHXLNFTGKDCMWB",
        "J",
    ),
    "V": (
        "VZBRGITYUPSDNHLXAWMJQOFECK",
        "Z",
    ),
    "VI": (
        "JPGVOUMFYQBENHZRDKASXLICTW",
        "ZM",
    ),
    "VII": (
        "NZJHGRCXMYSWBOUFAIVLPEKQDT",
        "ZM",
    ),
    "VIII": (
        "FKQHTLXOCBJSPDZRAMEWNIUYGV",
        "ZM",
    ),
}


REFLECTORS = {
    "B": "YRUHQSLDPXNGOKMIEBFZCWVJAT",
    "C": "FVPJIAOYEDRZXWGCTKUQSBNMHL",
}


def letter_to_index(letter: str) -> int:
    """Convert A-Z into 0-25."""
    return ord(letter) - ord("A")


def index_to_letter(index: int) -> str:
    """Convert any integer into a wrapped A-Z letter."""
    return ALPHABET[index % 26]


@dataclass
class Rotor:
    name: str
    ring: int = 0
    position: int = 0

    def __post_init__(self) -> None:
        wiring, self.notches = ROTOR_SPECS[self.name]

        self.forward_wiring = [
            letter_to_index(letter)
            for letter in wiring
        ]

        self.reverse_wiring = [0] * 26

        for input_pin, output_pin in enumerate(
            self.forward_wiring
        ):
            self.reverse_wiring[output_pin] = input_pin

    def at_notch(self) -> bool:
        """Return True when this rotor is at turnover."""
        return index_to_letter(self.position) in self.notches

    def step(self) -> None:
        """Advance the rotor by one position."""
        self.position = (self.position + 1) % 26

    def forward(self, signal: int) -> int:
        """Pass a signal from right to left."""
        shifted = (
            signal + self.position - self.ring
        ) % 26

        wired = self.forward_wiring[shifted]

        return (
            wired - self.position + self.ring
        ) % 26

    def reverse(self, signal: int) -> int:
        """Pass a signal back from left to right."""
        shifted = (
            signal + self.position - self.ring
        ) % 26

        wired = self.reverse_wiring[shifted]

        return (
            wired - self.position + self.ring
        ) % 26


class Plugboard:
    def __init__(self, pairs: str = "") -> None:
        self.mapping = list(range(26))
        used_letters = set()

        for pair in pairs.upper().split():
            if len(pair) != 2 or not pair.isalpha():
                raise ValueError(
                    f"Invalid plugboard pair: {pair!r}"
                )

            first, second = map(letter_to_index, pair)

            if first == second:
                raise ValueError(
                    "A letter cannot connect to itself."
                )

            if (
                first in used_letters
                or second in used_letters
            ):
                raise ValueError(
                    "A plugboard letter may appear "
                    "in only one pair."
                )

            self.mapping[first] = second
            self.mapping[second] = first
            used_letters.update((first, second))

        if len(used_letters) > 20:
            raise ValueError(
                "This example permits at most "
                "10 plugboard pairs."
            )

    def swap(self, signal: int) -> int:
        return self.mapping[signal]


class EnigmaMachine:
    def __init__(
        self,
        rotor_names=("I", "II", "III"),
        ring_settings="AAA",
        start_positions="AAA",
        reflector="B",
        plugboard_pairs="",
    ) -> None:
        if len(rotor_names) != 3:
            raise ValueError(
                "Exactly three moving rotors are required."
            )

        if len(set(rotor_names)) != 3:
            raise ValueError(
                "Choose three different rotors."
            )

        if len(ring_settings) != 3:
            raise ValueError(
                "Ring settings need three letters."
            )

        if len(start_positions) != 3:
            raise ValueError(
                "Starting positions need three letters."
            )

        self.left, self.middle, self.right = [
            Rotor(
                name=rotor_name,
                ring=letter_to_index(ring_letter),
                position=letter_to_index(start_letter),
            )
            for rotor_name, ring_letter, start_letter
            in zip(
                rotor_names,
                ring_settings.upper(),
                start_positions.upper(),
            )
        ]

        self.reflector = [
            letter_to_index(letter)
            for letter in REFLECTORS[reflector]
        ]

        self.plugboard = Plugboard(plugboard_pairs)

    def step_rotors(self) -> None:
        """
        Advance the rotors before enciphering.

        The middle rotor moves when the right rotor
        is at its notch or the middle rotor is at
        its own notch. At the middle notch, the
        left rotor advances too.
        """
        middle_at_notch = self.middle.at_notch()
        right_at_notch = self.right.at_notch()

        if middle_at_notch:
            self.left.step()

        if middle_at_notch or right_at_notch:
            self.middle.step()

        self.right.step()

    def encipher_letter(self, letter: str) -> str:
        self.step_rotors()
        signal = letter_to_index(letter)

        signal = self.plugboard.swap(signal)

        signal = self.right.forward(signal)
        signal = self.middle.forward(signal)
        signal = self.left.forward(signal)

        signal = self.reflector[signal]

        signal = self.left.reverse(signal)
        signal = self.middle.reverse(signal)
        signal = self.right.reverse(signal)

        signal = self.plugboard.swap(signal)

        return index_to_letter(signal)

    def process(
        self,
        text: str,
        preserve_nonletters: bool = True,
    ) -> str:
        output = []

        for character in text:
            upper = character.upper()

            if upper in ALPHABET:
                transformed = self.encipher_letter(upper)

                if character.islower():
                    transformed = transformed.lower()

                output.append(transformed)
            elif preserve_nonletters:
                output.append(character)

        return "".join(output)


encoder = EnigmaMachine(
    rotor_names=("I", "II", "III"),
    ring_settings="AAA",
    start_positions="AAA",
    reflector="B",
    plugboard_pairs="",
)

plaintext = "HELLOWORLD"
ciphertext = encoder.process(plaintext)


# Decryption needs a fresh machine at the original start.
decoder = EnigmaMachine(
    rotor_names=("I", "II", "III"),
    ring_settings="AAA",
    start_positions="AAA",
    reflector="B",
    plugboard_pairs="",
)

recovered = decoder.process(ciphertext)

print("Plaintext :", plaintext)
print("Encrypted :", ciphertext)
print("Decrypted :", recovered)

Expected output:

Plaintext : HELLOWORLD
Encrypted : ILBDAAMTAZ
Decrypted : HELLOWORLD

This is an educational model rather than a complete reconstruction of every Enigma family variant. It does, however, follow the same core route and reproduce the standard known-answer vector.

Reading the Code Like the Machine

Letters Become Numbers

The helper functions map A–Z to 0–25 and back:

def letter_to_index(letter: str) -> int:
    return ord(letter) - ord("A")
Letter Number
A 0
B 1
C 2
… …
Z 25

Each Rotor Stores Two Routes

The forward wiring travels towards the reflector. The reverse wiring is constructed by inversion:

for input_pin, output_pin in enumerate(
    self.forward_wiring
):
    self.reverse_wiring[output_pin] = input_pin

If the forward route maps A -> E, the reverse route must map E -> A.

Position and Ring Setting Shift the Signal

The input moves into the rotor's current frame:

shifted = (
    signal + self.position - self.ring
) % 26

The wiring is applied, then the shift is removed:

return (
    wired - self.position + self.ring
) % 26

This is the software equivalent of a fixed scrambled wiring inside a movable alphabet ring.

Stepping Happens Before the Circuit

self.step_rotors() is called before the first plugboard pass. The program records the right and middle notch states, moves the left rotor when the middle is at its notch, moves the middle when either relevant notch is engaged, and always advances the right rotor.

That explicit logic produces the middle-rotor double-step rather than an odometer approximation.

The Route Mirrors the Hardware

signal = self.plugboard.swap(signal)

signal = self.right.forward(signal)
signal = self.middle.forward(signal)
signal = self.left.forward(signal)

signal = self.reflector[signal]

signal = self.left.reverse(signal)
signal = self.middle.reverse(signal)
signal = self.right.reverse(signal)

signal = self.plugboard.swap(signal)

That sequence is Enigma in code.

Decryption Uses a Fresh Machine

After encryption, the first machine has moved away from its starting windows. The example constructs a second machine at the original AAA setting and processes the ciphertext through the same reciprocal operation.

This is not a separate decryption algorithm. It is the Enigma process replayed from the correct initial state.

Common Questions About Enigma

Was Enigma really unbreakable?

No. It was far stronger than simple hand ciphers, but its structure, procedures, predictable messages, human mistakes, and captured materials gave cryptanalysts ways to reduce the problem.

Did Alan Turing single-handedly crack Enigma?

No. Turing made fundamental contributions, especially to naval Enigma and the British Bombe, but the achievement built on pre-war Polish breakthroughs and depended on a vast international organisation of mathematicians, linguists, engineers, operators, intercept staff, military personnel, and intelligence analysts.

Is Enigma a code or a cipher?

Strictly, it is a cipher machine. A code replaces words, phrases, or concepts with code groups; a cipher transforms the symbols of a message according to a systematic rule. Enigma transforms letters.

Why can Enigma not encipher a letter as itself?

Its reflector joins contacts in reciprocal pairs without fixed points. The surrounding reversible permutations preserve that property.

Why does the same letter produce different outputs?

The right rotor advances before each processed letter, changing the electrical alignment. Turnover events also move the middle and left rotors.

Can Enigma encipher numbers?

The standard military alphabet contains 26 letters. Numbers must be written as words, represented through agreed conventions, or converted by a modern simulator's text-handling rules.

What is the difference between ring settings and starting positions?

Starting positions determine the letters visible in the windows. Ring settings offset the alphabet rings relative to the internal wiring. They are separate parts of the key.

Why must the receiver reset the rotors?

The rotors move during encryption. Decryption must recreate the same state sequence, so the receiver starts from the sender's original windows rather than the ending position.

What is the double-step?

Near turnover, the middle rotor can advance on two consecutive keypresses: first when pushed by the right rotor, then again at its own notch while moving the left rotor.

What is the difference between M3 and M4?

M3 has three moving rotors. M4 adds a stationary Beta or Gamma wheel beside a thin reflector while retaining three moving rotors.

Was the Bombe a computer?

Not in the modern general-purpose sense. It was a specialised electromechanical search machine that tested Enigma rotor hypotheses derived from a human-prepared crib and menu.

Could the Bombe read a message without a crib?

The standard Bombe attack depended on relationships derived from probable plaintext. The machine accelerated consistency testing, but human cryptanalytic preparation remained essential.

Is Enigma secure enough for private messages today?

No. Modern computers simulate and search Enigma configurations quickly, and the design is completely documented. Real secrets require modern authenticated encryption.

Why is Enigma still studied?

It connects mechanical engineering, permutations, modular arithmetic, state machines, operating procedure, human error, and cryptanalysis in one system that can be explored a letter at a time.

The Real Lesson of Enigma

Enigma should not protect passwords, private conversations, financial information, personal records, API keys, recovery phrases, or business secrets. Its structure is public, its historical weaknesses are extensively documented, and ordinary computers can reproduce what once required carefully manufactured electromechanical hardware.

It still deserves its central place in cryptographic history. Enigma shows that changing substitutions are stronger than fixed ones, that a cipher can be expressed as a composition of permutations, and that mechanical state can generate a changing sequence of transformations. It also shows how reversibility can simplify legitimate use while imposing structure, and why a vast number of written settings does not guarantee practical security.

The Germans did not merely trust three rotors. They trusted machines, plugboards, key sheets, message procedures, operators, networks, and the belief that the number of possibilities made systematic attack impossible.

The Allied codebreakers did not win by counting every possibility. They found structure, repetition, predictable language, contradictions, documents, and procedures. They built machines that tested the right questions faster than people could.

That is why Enigma still matters: not because it was invincible, and not because one genius solved it in a cinematic moment, but because its rise and fall reveal the lasting contest at the heart of cryptography.

One side builds complexity. The other searches for structure.

Sources and further reading

Try the Enigma Machine Simulator Tool

Want to experiment with the idea in practice? Open the matching tool and try your own text.

Open Enigma Machine Simulator
Signal acquired

A note from the team

We build these tools because we love cryptography, encoding, and making difficult ideas easier to explore. If they've helped you, even a small coffee means the world to the project. Thank you!

Say thanks on Ko-fi

Read next

Simulator Guide & Rotor Settings How to Use the Enigma Machine Simulator: Complete Guide A complete practical walkthrough of the CipherRegister Enigma simulator, from the first test vector to M4 keys, signal tracing, custom rotors, troubleshooting, and deciphering. Cryptanalysis Frequency Analysis: The Statistical Fingerprint That Broke Classical Ciphers How counting letters turned cryptanalysis from educated guesswork into a science, and why weak ciphers still betray themselves through the shape of language. Monoalphabetic Substitution Simple Substitution Cipher: Every Letter Wears a Mask How a scrambled alphabet became the simplest general form of classical substitution, and why the patterns of language still give it away.
Back to all articles