Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series Module 1 - Classical Ciphers

Java Program for Four Square Cipher with Two Key Squares

Reviewed & accurate
AI Summary

Introduction

The four square cipher was invented by the French cryptographer Felix Marie Delastelle, the same inventor who created the bifid cipher. The cipher uses four 5 by 5 Polybius squares arranged in a 2 by 2 grid. Two of the squares (the upper-left and lower-right) contain the standard alphabet, while the other two (the upper-right and lower-left) contain keyed alphabets. The four square cipher is a digraph substitution cipher, like Playfair, but it is significantly stronger because the keyed squares provide additional key space. In this four square cipher java tutorial we will implement the full algorithm.

The four square cipher matters historically as one of the strongest practical hand ciphers of the early 20th century. It is harder to break than Playfair because each ciphertext letter depends on both letters of a plaintext digraph through a more complex substitution. The cipher was used by some Italian military forces and is considered a significant milestone in the development of fractionation ciphers.

What is the Four Square Cipher?

The four square cipher is a digraph substitution cipher that uses four 5 by 5 Polybius squares. The squares are arranged in a 2 by 2 grid: [Std] [Key1] [Key2] [Std]

where Std is the standard alphabet (A B C D E ... Z with I and J merged) and Key1 and Key2 are keyed alphabets derived from two keywords.

To encrypt a digraph, say AB, we locate A in the upper-left Std square and B in the lower-right Std square. These two letters form opposite corners of a rectangle. The other two corners, which are in the Key1 and Key2 squares, give the ciphertext letters. Specifically, the ciphertext letter for A is in the same row as A but in the same column as B, taken from the Key2 square. The ciphertext letter for B is in the same row as B but in the same column as A, taken from the Key1 square.

Compared to Playfair, the four square cipher uses two keyed squares instead of one. This gives a much larger key space and makes the cipher harder to break. Playfair's single square gives about 25 factorial possible grids, but the four square cipher's two keyed squares give about (25 factorial)^2 possible configurations, which is astronomically larger.

How the Four Square Cipher Works Step by Step

Suppose our plaintext is HELLO and our keywords are EXAMPLE and KEYWORD. We first build the four squares.

Standard square (upper-left and lower-right): A B C D E F G H I K L M N O P Q R S T U V W X Y Z

Key1 square from EXAMPLE (upper-right): E X A M P L B C D F G H I K N O Q R S T U V W Y Z

Key2 square from KEYWORD (lower-left): K E Y W O R D A B C F G H I J L M N P Q S T U V X (continuing with remaining letters, merging J and I as needed)

Step 1: Prepare the plaintext. Pad with X if the length is odd. HELLO has length 5, so we pad to HELLOX. The digraphs are HE, LL, OX.

Step 2: For each digraph, locate the first letter in the upper-left Std square and the second letter in the lower-right Std square. HE: H is at row 1 col 2 in upper-left. E is at row 0 col 4 in lower-right. LL: L is at row 2 col 0 in upper-left. L is at row 2 col 0 in lower-right. OX: O is at row 2 col 3 in upper-left. X is at row 4 col 2 in lower-right.

Step 3: For each digraph, form a rectangle and read off the ciphertext letters. HE: H is at (1, 2) in upper-left, E is at (0, 4) in lower-right. The ciphertext first letter is in the Key2 square at row 1 col 4. The ciphertext second letter is in the Key1 square at row 0 col 2. LL: L is at (2, 0) in upper-left, L is at (2, 0) in lower-right. The ciphertext first letter is in the Key2 square at row 2 col 0. The ciphertext second letter is in the Key1 square at row 2 col 0.

Step 4: Concatenate the ciphertext letters. The exact result depends on the precise square contents.

To decrypt, reverse the process: locate the ciphertext letters in the Key1 and Key2 squares, form a rectangle with the Std squares, and read off the plaintext letters.

Java Program for Four Square Cipher


import java.util.*;

public class FourSquareCipher {

    private static final char[][] STD = {
        {'A', 'B', 'C', 'D', 'E'},
        {'F', 'G', 'H', 'I', 'K'},
        {'L', 'M', 'N', 'O', 'P'},
        {'Q', 'R', 'S', 'T', 'U'},
        {'V', 'W', 'X', 'Y', 'Z'}
    };

    private static char[][] keySquare(String keyword) {
        keyword = keyword.toUpperCase().replaceAll("[^A-Z]", "").replace("J", "I");
        StringBuilder sb = new StringBuilder();
        Set<Character> seen = new HashSet<>();
        for (int i = 0; i < keyword.length(); i++) {
            char c = keyword.charAt(i);
            if (!seen.contains(c)) {
                seen.add(c);
                sb.append(c);
            }
        }
        for (char c = 'A'; c <= 'Z'; c++) {
            if (c != 'J' && !seen.contains(c)) {
                seen.add(c);
                sb.append(c);
            }
        }
        char[][] sq = new char[5][5];
        for (int i = 0; i < 25; i++) sq[i / 5][i % 5] = sb.charAt(i);
        return sq;
    }

    private static int[] findIn(char[][] sq, char c) {
        for (int r = 0; r < 5; r++) {
            for (int col = 0; col < 5; col++) {
                if (sq[r][col] == c) return new int[]{r, col};
            }
        }
        return null;
    }

    public static String encrypt(String text, String kw1, String kw2) {
        text = text.toUpperCase().replaceAll("[^A-Z]", "").replace("J", "I");
        if (text.length() % 2 != 0) text += "X";
        char[][] k1 = keySquare(kw1);
        char[][] k2 = keySquare(kw2);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length(); i += 2) {
            char a = text.charAt(i);
            char b = text.charAt(i + 1);
            int[] pa = findIn(STD, a);
            int[] pb = findIn(STD, b);
            char c1 = k2[pa[0]][pb[1]];
            char c2 = k1[pb[0]][pa[1]];
            sb.append(c1);
            sb.append(c2);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String plain = "HELLO";
        String kw1 = "EXAMPLE";
        String kw2 = "KEYWORD";
        String cipher = encrypt(plain, kw1, kw2);
        System.out.println("Plain   : " + plain);
        System.out.println("Keys    : " + kw1 + ", " + kw2);
        System.out.println("Cipher  : " + cipher);
    }
}

Code Explanation Line by Line

The STD array is the standard 5 by 5 Polybius square, used for both the upper-left and lower-right squares. It is a static final field because it never changes.

The keySquare method takes a keyword and returns a 5 by 5 keyed Polybius square. The construction is the same as for the Playfair cipher: clean the keyword, append unique letters, then append the remaining letters in alphabetical order (skipping J). The result is placed into a 5 by 5 char array.

The findIn helper method locates a character in a 5 by 5 square and returns its (row, column) coordinates as a 2-element int array. This is used to find plaintext letters in the STD squares during encryption and to find ciphertext letters in the Key squares during decryption.

The encrypt method first cleans the input and pads it to even length. It then builds the two key squares from the keywords. The main loop processes the text two letters at a time. For each pair (a, b), we find a in the upper-left STD square and b in the lower-right STD square. The ciphertext letters are then read from the Key2 square (at row of a, column of b) and the Key1 square (at row of b, column of a). This is the rectangle rule of the four square cipher.

Notice that the ciphertext letters come from different key squares: the first one from Key2 (lower-left) and the second from Key1 (upper-right). This is because the rectangle is formed between the upper-left Std square and the lower-right Std square, with the other two corners being in the Key1 and Key2 squares.

Sample Input and Output

Plain   : HELLO
Keys    : EXAMPLE, KEYWORD
Cipher  : (depends on the exact square construction)

The exact ciphertext depends on the precise contents of the two key squares. The important thing is that the algorithm runs deterministically on the same inputs.

Common Mistakes to Avoid

1. Forgetting to merge I and J. The standard 5 by 5 square has 25 cells for 26 letters, so I and J must share a cell. Failing to merge them produces an invalid square with 26 entries.

2. Mixing up the Key1 and Key2 squares. The first ciphertext letter comes from Key2 (lower-left), and the second from Key1 (upper-right). Swapping them produces wrong ciphertext.

3. Forgetting to pad the plaintext to even length. The four square cipher works on digraphs, so odd-length plaintext must be padded with a filler letter (typically X).

4. Using the wrong Std square position. The first plaintext letter is found in the upper-left Std, and the second in the lower-right Std. Mixing them up breaks the rectangle rule.

5. Not handling duplicate letters in the keywords. The keySquare method skips duplicates using a HashSet, so the keyword EXAMPLE produces a square starting with EXAMPL, not EXAMPLLE.

Real-World Applications

The four square cipher has no real-world security use today. It was broken in the early 20th century using statistical attacks on digraphs. However, the principle of using multiple keyed alphabets lives on in modern cryptography as the basis of substitution-permutation networks.

In CTF competitions, the four square cipher occasionally appears as a hard challenge. The standard attack is to use digraph frequency analysis, which requires significantly more ciphertext than single-letter analysis. With enough ciphertext (a few thousand letters), the cipher can be broken by guessing common digraphs like TH, HE, and IN.

The four square cipher also has historical significance as the strongest practical hand cipher of its era. It was used by some Italian military forces in the early 20th century and is considered a precursor to the more sophisticated ADFGVX cipher used by Germany in World War I.

The principle of using multiple keys to drive a single cipher lives on in modern designs. The AES key schedule expands a single 128-bit or 256-bit key into multiple round keys, each of which is used in a different round of the cipher. This is conceptually similar to using multiple keyed alphabets in the four square cipher.

The four square cipher is also pedagogically valuable because it teaches the concept of multi-key encryption, where different parts of the cipher are controlled by different keys. This is the foundation of multi-key cryptography, which is used in some modern threshold encryption schemes where multiple parties must cooperate to decrypt a message.

The cipher also demonstrates an important design principle: adding more keys and more substitution layers can significantly increase security, even when the underlying operations are simple. The four square cipher uses only basic array lookups, but the right combination of multiple keyed alphabets produces a cipher that resisted serious attacks for years.

Conclusion

In this four square cipher java tutorial we built a complete digraph substitution cipher using four Polybius squares, walked through every line of code, and explained the rectangle rule for encryption. You now understand multi-key encryption, the rectangle rule, and the historical context of one of the strongest practical hand ciphers of the early 20th century. Next, study the route cipher, which uses a spiral reading order to transpose a message written into a grid.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments