Understanding the Enigma machine with 30 lines of Ruby. Star of the 2014 film “The Imitation Game”

by Albert Still

Scene from The Imitation Game 2014 filmI recently watched the film “The Imitation Game” and it’s brilliant despite Keira Knightley’s failed attempt at a posh British accent. Everyone should watch it especially if you’re interested in technology. It’s about the life of a genius called Alan Turing, he is also known as the father of modern computer science. That means the very tech you’re using to read this blog works on the foundations of his discoveries. His major breakthrough took place at GCHQ during WW2, he made a machine that decrypted secret German messages they sent using the Enigma machine. Furthermore, historians believe his work shortened the war by two years and saved thousands of lives. To me stories don’t get much more interesting than this, how us Brits used maths and computer science to help the Allies win WW2 and save Europe from fascism. 

After watching the film I became very interested in the Enigma machine and I’m going to use Ruby to explain to you how it works. If you don’t know the Ruby programming language don’t worry, you’ll be surprised how much syntax you understand. 

Journey of a single letterFirstly it’s important to realise the Enigma machine is just one big circuit. Each time a key is pressed at least one rotor is rotated which changes the circuitry of the machine thus lighting a different letter faced light bulb. The rotors are the only moving parts within the circuit and each have 26 steps, one for each letter of the alphabet. When a key is pressed the right rotor rotates by a step, when this reaches a full revolution the middle rotor rotates by a step, and when the middle rotor does a full revolution the left rotor rotates a step. Here is a video to best explain the circuitry:

I found the best way to understand the machine was to visualise the path of an electron traveling through the circuit after a key is pressed. First of all we get to the plugboard, here we literally swap 10 of the 26 letters. For example D becomes E and therefore E becomes D. In Ruby we can model this as Plugboard = Hash[*('A'..'Z').to_a.sample(20)] and then Plugboard.merge!(Plugboard.invert) so we can make it reflective. As for the 6 letters that are untouched and simply map to themselves we can make the value default to the entered key with Plugboard.default_proc = proc { |_, key| key }.

Next we get to the rotors, think of each of the rotors as a substitution cypher, each of its two sides has 26 metal contacts. And there is a mess of 26 wires inside that randomly pair the contacts. We can model a rotor as Hash[('A'..'Z').zip(('A'..'Z').to_a.shuffle)], for the return journey we can call invert on the hash before passing it a key.

The electron travels through all the rotors and then it gets to the reflector. The reflectors job is simply to turn the electron around and pass it back through the rotors. We can model it with Reflector = Hash[*('A'..'Z').to_a.shuffle] and Reflector.merge!(Reflector.invert).

It will now go back through the rotors, through the plugboard again and finally hit the letter faced lightbulb which would indicate to the operator what the letter had been encrypted or decrypted to, depending wether the operator is receiving or sending messages.

I have written a gist of an Enigma machine using the above code, please feel free to comment below if any of it needs explanation.

Why was it secure?

The Enigmas security comes from the large number of configurations the machine can be in. Every month German operators were issued a code book that told them what setting to put their plugboard and rotors in for each day of that month.

  • The Enigma machine came with 5 rotors to choose from and the machine used 3.  You have 5 to choose from, then 4, then 3. Order matters here therefore this yielded 5 x 4 x 3: 60 combinations.
  • Then each rotor has 26 starting positions. This yielded 26 x 26 x 2617,576  combinations.
  • The plugboard maths is more complicated, Andrew Hodges explains it well. The number of ways of choosing m pairs out of n objects is n! /((n-2m)! m! 2m). Therefore the enigma machine has (26! / ((26-2*10)! 10! 2^10): 150, 738, 274, 937, 250 combinations.

Shot of the Enigma machine in The Imitation Game 2014Multiply 60 x 17,576 x 150,738,274,937,250 and you have 158,962,555,217,826,360,000 combinations! And that is what GCHQ were faced with. They had to figure out which one of the combinations the Germans Enigma machines were using for that day so we could understand what the Germans were saying to each other. Furthermore the next day it would change making any promising work from the day before useless, a moving target!

This is where Turing’s master mind came in. Him and others built a bombe machine that speed up the process of working out what setting the Enigma machines were in for that day. First they tried guessing a small section of plaintext within the ciphertext, then the bombe was used to find the setting that would yield this plaintext through brut force. If I get the time I would love to study the bombe and try and write it in Ruby.

Did UX lose Germans the war?

The reflector was practical because it meant the Enigma machine operators used the same setting to send and receive messages. This was great but it also meant that a letter could never map to itself. This was a major weakness in the system, because it allowed the code breakers to eliminate possible solutions when the ciphertext and the putative piece of plaintext had the same letter in the same place. And it was this weakness Turing exploited with his bombe machine.

Why did they only use 10 pairs for the plugboard?

This puzzled me for a while, if you play around with the n! /((n-2m)! m! 2m) formula you will see 11 plug pairs yields the most combinations, with the number decreasing after 11. Here is the best explanation to why they used 10:

British cryptanalysts believed that the Germans chose 10 plugs because this resulted in the maximum number of plug-board permutations.  While the actual maximum occurs for 11 plugs, the discrepancy could well be a mistake in slide-rule computations on the part of the Germans.” — Deavours and Kruh (1985), “Machine Cryptography and Modern Cryptanalysis

So because they didn’t have computers back then doing maths with large numbers was difficult and had to be done by hand, and they simply believe it was a slide rule mistake.

Red Badger are hiring. Come join us

  • Timothy T

    In the embedded YouTube video at 10:37, the speaker says that 6 pairs of letters were chosen at system setup but in the enigma simulator wiring, you can see 10 pairs being swapped. What’s going on there?

    • Greg

      In the video is a new apple version – the engima mini

  • FaustoCarrera

    Alan Turing’s life is well documented, and the film is a deception, if you want to know more about cracking the enigma code, check the BBC documentary: Code-Breakers: Bletchley Park’s Lost Heroes.

    Marian Adam Rejewski, a Polish mathematician was the one who cracked the first German Enigma machine, and that’s the base Turing used to crack the new Enigma machine.

    The Turing approach to break the code was completely out of his time, a real genius.

    • Bobbyjoe Peener
    • Guest

      It’s a shame how often the Polish contribution gets overlooked, both in the film and this post.

      “how us Brits used maths and computer science to help the Allies win WW2 and save Europe from fascism.”

      And people say Americans take too much credit for the war.

      • Matthew Blott

        I’m afraid you’re talking bollocks. The author says “help the Allies” win the war. The word “help” denotes assistance rather than a primary role and the word “Allies” makes it clear it is a joint effort. Contrast that with your average bullshit Hollywood take where the only non American accents you’ll hear are by cannon fodder.

  • Pingback: Understanding the Enigma machine with 30 lines of Ruby. Star of the Oscar winning film "The Imitation Game" | infopunk.org()

  • J Tufts

    Perhaps you were trying to be funny about “Keira Knightley’s failed attempt at a posh British accent” but I thought it was in bad taste, especially since Keira Knightley is British and was nominated for an Academy Award for her role in “The Imitation Game”.

    • B B

      The author is British, and there are many accents that reside within the British English dialect. For example American English changes regions to region, city to city, and town to town. The New England accent and the New Orleans accent are both American accents, but very different from each other. The Author was making a joke that Kiera could not do a posh accent, which has its own particular sound.

    • George

      There’s no such thing as a British accent!!! If anything it was a posh English accent, which personally I didn’t find that offensive.

  • tooky

    You might enjoy having a go at the minusculus programming challenge: http://minisculuschallenge.com/index.html

  • Pingback: Understanding the Enigma machine | Felipe Contreras()

  • http://cad.cx Colin Dean

    I’m messing around with this in Scala over here: https://github.com/colindean/enigma-simulation

  • Dariusz Ostolski

    Rectification of some statements (I know that a pop culture move doesnt always reflect actuall history). The source of this text is from wikipedia and better reflects actual history: “Engima machine was first broken by Polish cryptologists Marian Rejewski, Jerzy Różycki and Henryk Zygalski, working for Polish military intelligence. Rejewski reverse engineered the device, using theoretical mathematics
    and material supplied by French military intelligence. Subsequently the
    three mathematicians designed mechanical devices for breaking Enigma
    ciphers, including the cryptologic bomb.
    From 1938 onwards, additional complexity was repeatedly added to the
    Enigma machines, making decryption more difficult and requiring further
    equipment and personnel—more than the Poles could readily produce. On 25 July 1939, in Warsaw, the Poles initiated French and British military intelligence representatives into their Enigma-decryption techniques and equipment, including Zygalski sheets
    and the cryptologic bomb, and promised each delegation a
    Polish-reconstructed Enigma. The demonstration represented a vital basis
    for the later British continuation and effort.[3]
    During the war, British cryptologists decrypted a vast number of
    messages enciphered on Enigma. The intelligence gleaned from this
    source, codenamed “Ultra” by the British, was a substantial aid to the Allied war effort.”

  • hugoharada

    Here is a brief explanation about the flaw in the design used to crack the code more rapidly…


  • Olalekan Sogunle

    Testing out the ruby, I tried some other plaintext, but the code only works for CAPITAL letters. If there are any small letters, it would disrupt the encoding. Can adjustments be made? And if I have ideas about it, can I work on it?

    • Albert Still

      The Engima was not meant to handle upper and lower case letters, it just had one keyboard with upper case letters marked on each of the 26 keys (see images http://goo.gl/Ab76lJ). Grammar would of been of little importance. You can do what you want with the code of course but I have not done the case sensitivity wrong.

      • Olalekan Sogunle

        Right, thanks for the clarification that the Enigma machine never had anything to do deal with upper and lower case letters. I must have not have gotten that piece from anywhere in the article. Then the code is sufficient for that purpose. But, what about creating an “Enigma machine” that takes care of the upper and lower case?

  • Chad

    Keira Knightly was born in, and currently resides in London. Maybe her “accent” just isn’t “posh” enough…