Enigma Machine Simulation

Introduction

The Enigma machine is a cipher device developed and used in the early- to mid-20th century to protect commercial, diplomatic, and military communication. It was employed extensively by Nazi Germany during World War II, in all branches of the German military. The Germans believed, erroneously, that use of the Enigma machine enabled them to communicate securely and thus enjoy a huge advantage in World War II. The Enigma machine was considered to be so secure that even the most top-secret messages were enciphered on its electrical circuits.

Enigma has an electromechanical rotor mechanism that scrambles the 26 letters of the alphabet. In typical use, one person enters text on the Enigma's keyboard and another person writes down which of 26 lights above the keyboard lights up at each key press. If plain text is entered, the lit-up letters are the encoded ciphertext. Entering ciphertext transforms it back into readable plaintext. The rotor mechanism changes the electrical connections between the keys and the lights with each keypress. The security of the system depends on a set of machine settings that were generally changed daily during the war, based on secret key lists distributed in advance, and on other settings that were changed for each message. The receiving station has to know and use the exact settings employed by the transmitting station to successfully decrypt a message.

Around December 1932, Marian Rejewski, a Polish mathematician and cryptanalyst, while working at the Polish Cipher Bureau, used the theory of permutations and flaws in the German military message encipherment procedures to break the message keys of the plugboard Enigma machine. Rejewski achieved this result without knowledge of the wiring of the machine, so the result did not allow the Poles to decrypt actual messages. The French spy Hans-Thilo Schmidt obtained access to German cipher materials that included the daily keys used in September and October 1932. Those keys included the plugboard settings. The French passed the material to the Poles, and Rejewski used some of that material and the message traffic in September and October to solve for the unknown rotor wiring. Consequently, the Polish mathematicians were able to build their own Enigma machines, which were called Enigma doubles. Rejewski was aided by cryptanalysts Jerzy Różycki and Henryk Zygalski, both of whom had been recruited with Rejewski from Poznań University. The Polish Cipher Bureau developed techniques to defeat the plugboard and find all components of the daily key, which enabled the Cipher Bureau to read German Enigma messages starting from January 1933. Over time, the German cryptographic procedures improved, and the Cipher Bureau developed techniques and designed mechanical devices to continue reading Enigma traffic. As part of that effort, the Poles exploited quirks of the rotors, compiled catalogues, built a cyclometer to help make a catalogue with 100,000 entries, invented and produced Zygalski sheets and built the electro-mechanical cryptologic bomba to search for rotor settings. In 1938, the Germans added complexity to the Enigma machines, leading to a situation that became too expensive for the Poles to counter. The Poles had six such bomby (plural of bomba), but when the Germans added two more rotors, ten times as many bomby were then needed, and the Poles did not have the resources. “There was no exact pattern in it which made it especially difficult to break."

Part One - Simulation

In this part I will be producing a simulation of an Enigma machine using Python.

The full code can be downloaded in the following gitbhub repository:
https://github.com/graham-blip/enigma/blob/main/enigma.py

Plug Leads

Let's start simulating the Enigma machine with the plugboard, specifically the leads. Each lead in the enigma machine connects two plugs in the plugboard. If we think of the functionality of the plugboard itself in terms of how it encodes a single character, the plugboard aggregates the leads, so it makes sense to make a class to represent the lead objects.

Write a class called PlugLead. The constructor should take a string of length two, which represents the two characters this lead should connect. So the following code:

lead = PlugLead("AG")

creates a lead which connects A to G. Remember leads are reversible so this lead also connects G to A.

If you are still new to object-oriented design, when you are first conceptualising a class, you should take some time to think about what attributes it has and what methods it has.

A method called encode(c) was emplemented on the lead, which takes a single character c, and returns the result of this lead on this character.

So, with the lead object I created above, lead.encode("G") should return "A".

lead.encode("D") should return "D" – this lead had no impact on the letter D, it only connects A and G.

Of course even though it would have no effect, it is not possible to connect a letter to itself – there is only one plug for each letter on the plugboard. For this assignment you should write your code to be robust, obeying the physical limitations of the Engima machine.

Plugboard

Naturally we now need the plugboard itself to house our leads.

An interesting part of object-oriented design is the idea that the interface of the object is really all an outsider needs to know. In the previous part we asked you to ensure a lead object supports .encode("A"), but how you achieve that is up to you.

With all that in mind, I wrote a class called Plugboard. The plugboard accepts leads which connect plugs via the method .add(…) as demonstrated below.

Like the leads, the plugboard should have an .encode(…) method as well, which returns the result of passing the character through the entire plugboard.

These are the only interface requirements, but you are encouraged to elaborate on these with additional methods and/or constructor keywords.

Remember that the Enigma machine only came with 10 leads to connect plugs.

Rotors

The number of possible combinations due to the plugboard is staggering, making brute force attempts to break a code extremely difficult. But using it alone would result in a simple substitution cipher – easily cracked with techniques like frequency analysis. The next step in the process, the rotors, allow the letter substitution to change mechanically every time a key is pressed, which prevents simple frequency analysis.

Over time, rotors with many different wiring patterns were developed, and different Enigma machines supported different types and numbers of rotors. We are not necessarily looking for exact historical accuracy in this assignment – for your extension material you might choose to be much more accurate or much less accurate! For this part, you should work on the following specification.

The Enigma machine supports three or four rotors and one reflector – notice that a reflector is really just a type of rotor where the characters line up in 13 perfect pairs. The rotors will be numbered from right to left, which is the “path” the current takes when first entering the rotors. The signal goes through each rotor in turn, hits the reflector, then goes through the rotors again in reverse order (left to right). When it goes through the rotors in reverse order, it uses the reverse wiring. So if A is mapped to L when going from right to left, then L is mapped to A on the reverse journey (of course it is not possible to actually hit the same wire on the way back – a letter cannot encode into itself in the machine as a whole).

Ignoring reflectors, which never rotate, there are two types of rotating rotor, based on whether or not the rotor contains a notch. If the rotor contains a notch, then when it is on a certain position and is rotated, it will cause the rotor in the next slot to rotate as well. In addition, in a four slot Engima machine, the leftmost (fourth) rotor never rotates. Rotation will be explained in more detail shortly.

Each rotor can be chosen from a box containing seven possible wiring patterns. There are two rotors labelled Beta and Gamma. Then there are five rotors labelled with Roman numerals which do rotate: I, II, III, IV, V. You must also support three possible reflector wiring patterns, labelled A, B, C.

Note: the wiring patterns are all real, taken from this page. The page contains more rotors if you wish to consider them, or you can make up your own, but you must support the ones here. The following patterns all assume the rotors are in their default position, with their default ring setting, and going from right to left (the initial path).

Mapping from letter
LabelABCDEFGHIJKLMNOPQRSTUVWXYZ
BetaLEYJVCNIXWPBQMDRTAKZGFUHOS
GammaFSOKANUERHMBTIYCWLQPZXVGJD
IEKMFLGDQVZNTOWYHXUSPAIBRCJ
IIAJDKSIRUXBLHWTMCQGZNPYFVOE
IIIBDFHJLCPRTXVZNYEIWGAKMUSQO
IVESOVPZJAYQUIRHXLNFTGKDCMWB
VVZBRGITYUPSDNHLXAWMJQOFECK
AEJMZALYXVBWFCRQUONTSPIKHGD
BYRUHQSLDPXNGOKMIEBFZCWVJAT
CFVPJIAOYEDRZXWGCTKUQSBNMHL

Single Rotor Demonstration

Rotors still get bit more complicated when we introduce their settings and put multiple in the same machine.

In the cell below, it demonstrates some basic rotor functionality using the classes.

The Enigma Machine

To fully understand rotors, we need to imagine multiple of them in the Enigma machine itself. For this next part, you will need to model many more details of how the rotors work, and in addition work out how to incorporate them into a single machine that is capable of performing the full encoding path.

Multiple Rotors

For now, let's ignore the plugboard, and introduce the remaining details for the rotors.

It is common to see the selection of rotors specified in a single sequence from left to right, as the operator would see when looking down, such as on a German code book. For example, on the top row of that linked image, you can see the rotors should be I V III. This means the first (rightmost) rotor is III, and so on. How you conceptualise the order inside your code is up to you providing it is consistent with the terminology here.

The code book also specifies each rotor's “ring setting” – in that image you can see the rotors on the top line should be set to 14 09 24 correspondingly.

The rotor settings will be explained later, but let's first ensure you understand the way the wiring works with multiple rotors. We will show a worked example using three rotors, with all the settings in their default positions – this means you can read the character mappings directly from the table above.

Imagine a III rotor sat upright in the machine in the right hand position. The right hand side of the rotor has 26 pins and the left hand side has 26 contacts, one for each character. The pins on the right are connected to the contacts of the rotor housing which is wired into the plugboard. So if the plugboard sends a signal on the A contact of the housing, then this hits the A pin of the rotor, then this passes through the rotor's internal wiring (check the table for the III rotor) and we receive an output signal on the B contact of the rotor. This will now go into the next rotor: remember there are three or four rotors, followed by a reflector.

Suppose there is a II rotor in the middle position, a I rotor in the left position, and then a B reflector. Here is the full path when we send an A signal from the plugboard:

The final output for this A signal is a U. Make sure you can follow this using the table above, as things are about to get more complicated.

Rotation

As mentioned, the rightmost rotor (first in the order of the electrical circuit) rotates at the start of each keypress, i.e. before the character signal is passed through the circuit. This is what makes the Enigma machine more powerful than a fixed substitution cipher, one rotation causes a completely different circuit and substitution.

The rotation of the rotor advances a setting called the position of each rotor, which is visible through a window on the machine. This setting is marked on the rotor and is a character between A and Z, but it is helpful to think of this number as an offset rather than a letter. In the example above we assumed all of the rotors were set to position A. Rotating moves the pins and the contacts up by one position (A becomes B, etc).

We mentioned before that if we input A into the III rotor in its default position (which is labelled A) then it produces an output of B. In our full example we assumed that the rotors were set to AAA, but if we set them this way on the machine, then as soon as we press the A key the rightmost rotor would rotate giving AAB, and this is the circuit that would be made (rotation always happens first). Let's look at what happens in this setting.

Now if we input an A signal from the plugboard, it will come out of the A contact of the housing, but it will hit the B pin of the rotor due to its rotation by one position. The B pin is wired to the D contact (reading from the table).

But the D contact has also been rotated one position inside the machine, so it actually lines up with the C pin of the next rotor in its default position. The other two rotors and the reflector work as normal, and on the way back rotor II sends a signal on its E pin. Since III is rotated, this hits the F contact which is wired to the C pin. But again since it is rotated, this his the B contact of the rotor housing, and is what is sent back to the plugboard.

Here is the full example again, now assuming the rotors are set to AAB instead of AAA:

You can try using the Enigma machine emulator on this page. It defaults to the same settings: rotors I II III all initially set to position A, so when you press the A key on the keyboard you should get B.

Make sure you can follow this path using the table of wirings to help you understand how you will implement the behaviour. If you simply do not follow, there are lots of explanations and videos online for Enigma machines.

Ring Settings

In addition each rotor could be configured by changing the ring setting, which is a fixed offset that would apply between the internal wiring and the external markings. The ring settings were either given from A-Z or 01-26 – you saw the latter in the code book image linked above, and we'll use these too to avoid confusion with the position setting.

If a rotor's ring setting is set to 01 then nothing is changed, the wiring is exactly as written in the table above.

Increasing the ring setting has the exact same effect as decreasing the position setting. It shifts the internal wiring in the opposite direction.

Earlier we said A becomes U with the given rotors actually set to AAA – we'd have to start on AAZ to get this result on the machine, since the rotation happens first (try it on the emulator). Alternatively, we could set the ring position to 02 on the rightmost rotor and set the initial positions to AAA, and we'll get the same result for a single press (again you can try this on the emulator; it uses letters for ring settings, if you click the rotor you can set the ring setting to B).

If we keep pressing A, the two configurations will produce many of the same characters, but not always. We have detailed how the rightmost rotor rotates, but not the others, and this detail will eventually produce a difference between the two sets of settings above.

Turnover

The rotors labelled I to V have notches. If a rotor has a notch and is currently set to its notch position, then it will turn the next rotor on the next keypress (this is called turnover). Here are the notch positions:

RotorNotch
IQ
IIE
IIIV
IVJ
VZ

So if a II rotor in the first, rightmost, slot of the machine is currently set to position E then when you press a key the first rotor will turn to position F and the rotor in the second position will turn as well, and then the electrical signal will be sent through the circuit.

If the II rotor had been in the second position, then it will obviously turn much more slowly. But if its position is set to E and a key is pressed then it will rotate and turn the rotor in the third position also.

There is an important detail here called the double step. Normally the second rotor will only turn once every 26 turns of the rightmost rotor. But if the second rotor is on its notch setting, then it will turn again as it turns the third rotor. Obviously the second rotor must have just rotated to land on its notch, so it actually rotates for two keypresses in a row.

Suppose we have the rotors I II III, on positions A C U. Pressing a key turns the III rotor and we get A C V. Now the III rotor is on its notch, so pressing a key also turns II and we get A D W. If we continue pressing keys we'll get A D X, A D Y, A D Z, A D A, and so on. Several keypresses later we wrap round again and approach the notch on III again on setting A D U. When we press once we get A D V. Now III is on its notch so pressing again turns II and we get A E W. But now II is on its notch, so when we press again all three rotors rotate and we get B F XIII turns because it always turns, II turns because it is on its notch, and I turns because II turned on its notch (turnover).

Notice the ring setting is inconsequential in this turnover process – it only requires the current position to line up with the notch setting.

The four-rotor machines did not have a additional lever, and so whether the third rotor had a notch or not the fourth rotor would not turn. In addition if a notchless rotor (e.g. Beta) was in the first position, then it will never cause the second rotor to rotate. The rightmost rotor will still always rotate exactly once on every keypress. Notchless rotors can still be set to different position settings as part of the setup process.

If you are curious about the mechanism, you can see a video of a mock-up version of an Enigma machine in action here, showing how the the ratchets, levers, and notches contribute towards the rotation on each keypress, and also demonstrating the double step (around 26 seconds into the video).

Multiple Rotor Demonstration

In the cell below, demonis demondstrates that the rotors work. It shows the following:

Enigma Machine Demonstration

Now in the cell below, it demonstrates that all of the elements can be put together. The full Engima machine supports a plugboard with up to 10 leads, three or four rotors, and a reflector. In addition it is able to encode an entire string of characters made from the letters A-Z, correctly advancing the rotors.

Example 1

A set up of enigma machine with rotors I II III, reflector B, ring settings 01 01 01, and initial positions A A Z.

The plugboard should map the following pairs: HL MO AJ CX BZ SR NI YW DG PK.

The result of encoding the string HELLOWORLD should be RFKTMBXVVW.

Example 2

A set up of enigma machine with rotors IV V Beta I, reflector A, ring settings 18 24 03 05, and initial positions E Z G P.

The plugboard should map the following pairs: PC XZ FM QA ST NB HY OR EV IU.

Find the result of decoding the following string: BUPXWJCDPFASXBDHLBBIBSRNWCSZXQOLBNXYAXVHOGCUUIBCVMPUZYUUKHI.

Part Two – Code Breaking

In this part of the projet it takes some ciphertext that has been encrypted using an Enigma machine, an idea of what the original text might contain (a crib), and some partial information about the machine. The goal will be to provide the original plaintext and the full machine settings.

The Bletchley codebreakers were able to combine weaknesses in the machine's encryption, mathematical techniques, and computing power to solve German codes.

The number of possible settings for Enigma is still too vast to break a code through brute force alone, but you can use the partial information to narrow the search into something feasible on a modern computer. Even on weaker hardware, none of the codes will require more than a few minutes maximum with suitable code.

Codes

Each code contains the ciphertext (the encrypted text), and a crib: a word or phrase that you think appears exactly somewhere within the original text.

The machines in this section will only ever use 3 rotors – meaning 3 ring settings and 3 starting positions also.

Code 1

You recovered an Enigma machine! Amazingly, it is set up in that day's position, ready for you to replicate in your software. But unfortunately the label has worn off the reflector. All the other settings are still in place, however. You also found a book with the title "SECRETS" which contained the following code, could it be so simple that the code contains that text?

Code 2

A university department has intercepted a message from the admissions team. They know it contains the word "THOUSANDS" and they are worried it might relate to how many students are arriving next semester. But the admissions team are a bit unusual: they love even numbers, and hate odd numbers. You happen to know they will never use an odd-numbered rotor, ruling out I, III, and V. They will also never use a ring setting that has even a single odd digit: 02 is allowed but 11 is certainly not, and even 12 is banned.