A java implementation of Enigma, and a modern attack to decrypt it.

Related tags


Java Enigma

This is a Java implementation of an Enigma machine, along with code that attempts to break the encryption. This code is associated with an upcoming Computerphile video.

The Enigma Machine

An enigma machine is a mechanical encryption device that saw a lot of use before and during WW2. This code simulates a 3 rotor enigma, including the 8 rotors commonly seen during the war.

Creating a Java Enigma

The code itself is fairly straightforward. You can create a new enigma machine using a constructor, for example:

enigmaMachine = new Enigma(new String[] {"VII", "V", "IV"}, "B", new int[] {10,5,12}, new int[] {1,2,3}, "AD FT WH JO PN");

Rotors and the reflector are given by their common names used in the war, with rotors labelled as "I" through to "VIII", and reflectors "B" and "C". I've not implemented every variant, such as the thin reflectors seen in naval 4-rotor enigma. You could easily add these if you liked. Starting positions and ring settings are given as integers 0-25 rather than the A-Z often seen, this is just to avoid unnecessary mappings. The majority of the code here treats letters as 0-25 to aid indexing. Plugs are given as a string of character pairs representing steckered partners. If you don't wish to use a plugboard, "" or null is fine.

Encrypting and Decrypting

Given an enigma instance, encryption or decryption is performed on character arrays of capital letters [A-Z]. Simply to save time I've not done a lot of defensive coding to remove invalid characters, so be careful to only use uppercase, or to strip unwanted characters out of strings. Here is an encryption example using the enigma machine above:

char[] plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
char[] ciphertext = enigmaMachine.encrypt(plaintext);
String s = new String(ciphertext); // UJFZBOKXBAQSGCLDNUTSNTASEF

You can quickly check everything is working by running the tests found in the EnigmaTest.java file.

How it works

Throughout the enigma machine, letters A-Z are represented as integers 0-25. Most of the components, the rotors, reflector and plugboard are treated as arrays that map values 0-25 to a different set of values 0-25. Encrypting or decrypting is simply a case of passing a value through these arrays in turn. What makes enigma trickier is that the arrays rotate, and that they can have different starting or ring positions. For efficiency in this implementation I keep the arrays fixed, and simulate rotation by shifting the index in and out of each rotor. Before each character is encrypted the rotors rotate, sometimes causing the neighbouring rotors to also rotate, this is handled by the rotate() function. Enigma has a quirk whereby the middle rotors moves twice when it turns the left-most rotor. This is called double stepping, and is also implemented here.

Breaking a Code

Breaking an enigma message here comes down to decrypting a ciphertext with all possible rotor configurations and seeing which output looks the best. We measure best here using a fitness function.

Fitness functions

The code makes a number of fitness functions available that can be used to measure how close a test decryption is to English text. Each works similarly, some work better than others. You can test to see which work best for a given message. The fitness functions are:

  • Index of coincidence. The probability of any random two letters being identical. Tends to be higher for proper sentences than for random encrypted text
  • Bi / Tri / Quad grams. The probability of a sentence measured based on the probability of constituent sequences of characters. Bigrams are pairs, such as AA or ST. Trigrams are triplets, e.g. THE, and so on.
  • Plaintext Fitness. This function is a known plaintext attack, comparing the decryption against all or portions of a suspected real plaintext. This is by far the most effective solution, even a few words of known plaintext will substantially increase your odds of a break even with a number of plugboard swaps.

Ciphertext Analysis

All the code required to crack enigma messages is found the analysis package, and an example (used in the Computerphile video) is in the main() method. The basic approach is as follows:

  1. Decrypt the ciphertext with every possible rotor in each position, and rotated to each starting position. All rotor ring settings are set to 0. No plugboard. For each decryption, measure the text fitness using one of the available fitness functions. Save the best performing rotor configuration.
  2. Fix the rotors, and iterate through all possible ring settings for the middle and right rotors, again testing the fitness of the decryption. You do not have to use the same fitness function as before.
  3. Fix all settings, and then use a hill climbing approach to find the best performing plugboard swaps, again measured using a fitness function.


  • The code is fairly efficient, Enigma boils down to a lot of array indexing into different rotors. This said, I didn't worry too much about speed, it's plenty fast enough. I used classes and functions rather than doing things inline, for example. Modern compilers will optimise a lot of it anyway.
  • Similarly, in the brute force key search code, for simplicity I create new enigma machines as required rather than implementing a number of specific reinitialisation functions that would be faster.
  • I've not written any kind of command line parsing here. You're welcome to add this, but i felt for a tutorial on enigma and breaking it, a step by step procedure in main was fine.


  1. For more details on enigma, the wikipedia articles are a great resource.

  2. This attack is a variant of that originally proposed by James Gillogly. His work on this is still available via the web archive here.

  3. If you'd like a more visual example of both encryption and cracking enigma codes, the Cryptool project is a great tool for this. Cryptool 2 has a great visualiser and can run cracking code similar to my own. I used cryptool to write the tests I used to make sure my own enigma implementation was working.

  • Instructions aren't clear

    Instructions aren't clear

    I'm a novice, having not done any programming in 20 years. I've installed JDK, and compiled Main.java.

    When I run java com.mikepound.Main, I get:

    Exception in thread "main" java.lang.NullPointerException at java.io.Reader.(Unknown Source) at java.io.InputStreamReader.(Unknown Source) at com.mikepound.analysis.fitness.BigramFitness.(BigramFitness.java:21) at com.mikepound.Main.main(Main.java:14)

    I don't understand how to "create a java enigma" using a constructor

    "enigmaMachine = new Enigma(new String[] {"VII", "V", "IV"}, "B", new int[] {10,5,12}, new int[] {1,2,3}, "AD FT WH JO PN");"

    If you could dumb down your instructions for the absolute rookies among us, that would be awesome.

    opened by stretchkerr 5
  • NOT A ISSUE - more of a comment/thanks

    NOT A ISSUE - more of a comment/thanks

    Hello; First of all I want to say that - Computerphile - is amazing, and You are Extremely Good at Explaining things! I always watch videos with you in them; And this enigma git, is just - amazing.

    Great work! Keep it up! And,

    Have a Great Corona-Free Year!


    opened by loneicewolf 1
  • When some plaintext is known?

    When some plaintext is known?

    Hi Mike,

    Love the videos, and in this case its great that you have provided the code. Brilliant!

    Anyway, I'm not a Java developer, but I'm trying to get through this with my C and Python knowledge. I was trying to see if I could get known bits of plain text to improve the matching of the settings? The idea being that once you've got the sudo text out, if you can identify strings that you think are correct, you can feed these back in.

    I tried adding this in, but I may be well off on what I'm doing here (Java at least part of the barrier). Any chance of an example involving some plain text, and how it might improve finding the settings?

    +      String[] known_str=new String[] {"PROPOSE", "CONSIDER", "QUESTION"};
    +      int[] intArray = new int[] { 1, 10, 21};
            FitnessFunction ioc = new IoCFitness();
            FitnessFunction bigrams = new BigramFitness();
            FitnessFunction quadgrams = new QuadramFitness();
     +     FitnessFunction knownplain = new KnownPlaintextFitness(known_str, intArray);

    Oh, and another quick question, in your example decrypted text, it looked (although its not fully decoded) like there are no spaces, I know that Enigma didn't have spaces, but I've read other places that someone could use X. Is the presence of Xs as spaces or something else a vulnerability to the encoding? Colin

    opened by byteduty 1
Michael Pound
Assistant Professor in Computer Science
Michael Pound
AES-GCM encryption/decryption for React Native

react-native-aes-gcm-crypto AES-GCM encryption/decryption for React Native Requirements iOS >= 13.0 Android >= 26 Installation npm install react-nativ

Takuya Matsuyama 35 Mar 25, 2021
Password strength estimator

Nbvcxz - Password strength estimator - [] nbvcxz is java library (and standalone console program) which is heavily inspired by the work in zxcvbn. Pas

GoSimple 204 Mar 12, 2021
Fluent builders with typesafe API for the JCA

Security Builders This library implements a set of "fluent" API builders for the java.security classes, and provides more typesafe, intuitive API to a

Terse Systems 39 Mar 11, 2021
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.2k Mar 12, 2021
CTFCrackTools 's BurpSuite Plugin - Decode and Encode

DaE - Decode and Encode CTFCrackTools 's BurpSuite Plugin - Decode and Encode Many people suggested that I develop BurpSuite version, so I ported this

0chen 31 Feb 26, 2021
破解 Java 混淆工具 Allatori

AllatoriCrack 基于当前最新的 7.6 版本 简介: 破解 Java 混淆工具 Allatori 官网 并进行了部分加密功能的小修改 allatori 本身使用方法特别简单 命令行输入 java -Xms128m -Xmx512m -jar allatori.jar config.xml

null 19 Mar 17, 2021
Open Source Identity and Access Management For Modern Applications and Services

Keycloak Keycloak is an Open Source Identity and Access Management solution for modern Applications and Services. This repository contains the source

Keycloak 8.4k Mar 13, 2021
Java JWT: JSON Web Token for Java and Android

Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand library for creating and verifying JSON Web Tokens (JW

null 7.3k Mar 13, 2021
Password4j is a user-friendly cryptographic library that supports Argon2, Bcrypt, Scrypt, PBKDF2 and various cryptographic hash functions.

Password4j is a Java user-friendly cryptographic library for hashing and checking passwords with different Key derivation functions (KDFs) and Cryptog

Password4J 123 Mar 2, 2021
Hdiv CE | Application Self-Protection

New to Hdiv? Check this out Hdiv: Application Self-Protection Hdiv is a leading provider of open source software for real-time, self-protected applica

Hdiv 195 Feb 10, 2021
Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.

Tink A multi-language, cross-platform library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse. Ubuntu

Google 11.1k Mar 13, 2021
Okta Spring Boot Starter

Okta Spring Boot Starter Okta's Spring Boot Starter will enable your Spring Boot application to work with Okta via OAuth 2.0/OIDC. Release status This

Okta, Inc 195 Mar 12, 2021

Okta Java Authentication SDK Release status Need help? Getting started Usage guide Configuration reference Building the SDK Contributing The Okta Auth

Okta, Inc 22 Mar 10, 2021
Bouncy Castle Java Distribution (Mirror)

The Bouncy Castle Crypto Package For Java The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms, it was developed by t

Legion of the Bouncy Castle Inc 1.4k Mar 14, 2021