From ce897bd66d5c996e3d0707879650b2cdefe6a03e Mon Sep 17 00:00:00 2001 From: Aditya Kulkarni <213192267+Aditya2375@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:57:48 +0530 Subject: [PATCH 1/2] fix: make ADFGVX decrypt handle partial last rows and repeated key letters reverseColumnarTransposition assumed every column had the same length, but the last grid row is partial, so decrypt garbled any message whose fractionated length was not a multiple of the key length (HELLO/PRIVACY came back as S35LL). Column order also used key.indexOf, so repeated key letters aliased one column and POLYBIUS_MAP misses leaked the literal text "null" into the output. Compute per-column lengths, order columns by (letter, first occurrence), and throw IllegalArgumentException on ciphertext that is not valid ADFGVX output. --- .../thealgorithms/ciphers/ADFGVXCipher.java | 71 +++++++++++++------ 1 file changed, 49 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java b/src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java index d915858f9e6f..a7242b7a0da4 100644 --- a/src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java @@ -80,10 +80,18 @@ public String encrypt(String plaintext, String key) { public String decrypt(String ciphertext, String key) { String fractionatedText = reverseColumnarTransposition(ciphertext, key); + if (fractionatedText.length() % 2 != 0) { + throw new IllegalArgumentException("Invalid ciphertext: odd number of ADFGVX letters."); + } + StringBuilder plaintext = new StringBuilder(); for (int i = 0; i < fractionatedText.length(); i += 2) { String pair = fractionatedText.substring(i, i + 2); - plaintext.append(POLYBIUS_MAP.get(pair)); + Character letter = POLYBIUS_MAP.get(pair); + if (letter == null) { + throw new IllegalArgumentException("Invalid ciphertext: unknown ADFGVX pair \"" + pair + "\"."); + } + plaintext.append(letter); } return plaintext.toString(); @@ -110,11 +118,7 @@ private String columnarTransposition(String text, String key) { // Read columns based on the alphabetical order of the key StringBuilder ciphertext = new StringBuilder(); - char[] sortedKey = key.toCharArray(); - Arrays.sort(sortedKey); - - for (char keyChar : sortedKey) { - int column = key.indexOf(keyChar); + for (int column : columnsInKeyOrder(key)) { for (char[] row : table) { if (row[column] != '_') { ciphertext.append(row[column]); @@ -125,6 +129,24 @@ private String columnarTransposition(String text, String key) { return ciphertext.toString(); } + /** + * Returns the column indices in the order the key imposes: alphabetical by + * key letter, with repeated letters ordered by their first occurrence. + * Using key.indexOf for repeated letters would map both occurrences to the + * same column and make the transposition lossy. + */ + private int[] columnsInKeyOrder(String key) { + Integer[] order = new Integer[key.length()]; + for (int i = 0; i < order.length; i++) { + order[i] = i; + } + Arrays.sort(order, (a, b) -> { + int byLetter = Character.compare(key.charAt(a), key.charAt(b)); + return byLetter != 0 ? byLetter : Integer.compare(a, b); + }); + return Arrays.stream(order).mapToInt(Integer::intValue).toArray(); + } + /** * Helper method: Reverses the columnar transposition during decryption * @@ -133,31 +155,36 @@ private String columnarTransposition(String text, String key) { * @return The reversed text */ private String reverseColumnarTransposition(String ciphertext, String key) { - int numRows = (int) Math.ceil((double) ciphertext.length() / key.length()); - char[][] table = new char[numRows][key.length()]; + int numCols = key.length(); + int fullRows = ciphertext.length() / numCols; + int remainder = ciphertext.length() % numCols; + // The last row of the encryption table is only partially filled: the + // first `remainder` columns hold one extra character. The previous + // implementation assumed every column had the same length, which + // misaligned the whole grid whenever the length was not a multiple of + // the key length. + int[] columnLength = new int[numCols]; + for (int column = 0; column < numCols; column++) { + columnLength[column] = fullRows + (column < remainder ? 1 : 0); + } - char[] sortedKey = key.toCharArray(); - Arrays.sort(sortedKey); + int numRows = fullRows + (remainder > 0 ? 1 : 0); + char[][] table = new char[numRows][numCols]; int index = 0; // Populate the table column by column according to the sorted key - for (char keyChar : sortedKey) { - int column = key.indexOf(keyChar); - for (int row = 0; row < numRows; row++) { - if (index < ciphertext.length()) { - table[row][column] = ciphertext.charAt(index++); - } else { - table[row][column] = '_'; - } + for (int column : columnsInKeyOrder(key)) { + for (int row = 0; row < columnLength[column]; row++) { + table[row][column] = ciphertext.charAt(index++); } } // Read the table row by row to reconstruct the fractionated text StringBuilder fractionatedText = new StringBuilder(); - for (char[] row : table) { - for (char cell : row) { - if (cell != '_') { - fractionatedText.append(cell); + for (int row = 0; row < numRows; row++) { + for (int column = 0; column < numCols; column++) { + if (row < columnLength[column]) { + fractionatedText.append(table[row][column]); } } } From 47a6656a218d9cdb01cd6b227349921ed244d3a6 Mon Sep 17 00:00:00 2001 From: Aditya Kulkarni <213192267+Aditya2375@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:58:52 +0530 Subject: [PATCH 2/2] test: cover ADFGVX round trips with partial last rows and repeated key letters Regression tests for the decrypt fix: a message whose fractionated length is not a multiple of the key length must round-trip, a key with repeated letters must round-trip, and invalid ciphertext must throw IllegalArgumentException instead of leaking "null". --- .../ciphers/ADFGVXCipherTest.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/test/java/com/thealgorithms/ciphers/ADFGVXCipherTest.java b/src/test/java/com/thealgorithms/ciphers/ADFGVXCipherTest.java index 4db856e40b84..09a501a88a4f 100644 --- a/src/test/java/com/thealgorithms/ciphers/ADFGVXCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/ADFGVXCipherTest.java @@ -43,4 +43,28 @@ void testShortKey() { String decrypted = adfgvxCipher.decrypt(encrypted, key); assertEquals("TESTING", decrypted); } + + @Test + void testRoundTripWhenLengthIsNotMultipleOfKeyLength() { + // "HELLO" fractionates to 10 ADFGVX letters; 10 % 7 != 0, so the last row of + // the transposition grid is partial. This used to decrypt to "S35LL". + String key = "PRIVACY"; + String encrypted = adfgvxCipher.encrypt("HELLO", key); + assertEquals("HELLO", adfgvxCipher.decrypt(encrypted, key)); + } + + @Test + void testRoundTripWithRepeatedLettersInKey() { + // indexOf-based column order maps both Bs and both As to the same column, + // which used to corrupt the message and leak "null" into the output. + String key = "BADCAB"; + String encrypted = adfgvxCipher.encrypt("ATTACKATDAWN", key); + assertEquals("ATTACKATDAWN", adfgvxCipher.decrypt(encrypted, key)); + } + + @Test + void testDecryptRejectsInvalidCiphertext() { + // Z is not an ADFGVX letter; the old code silently appended "null". + org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> adfgvxCipher.decrypt("ZZ", "KEY")); + } }