@@ -80,10 +80,18 @@ public String encrypt(String plaintext, String key) {
8080 public String decrypt (String ciphertext , String key ) {
8181 String fractionatedText = reverseColumnarTransposition (ciphertext , key );
8282
83+ if (fractionatedText .length () % 2 != 0 ) {
84+ throw new IllegalArgumentException ("Invalid ciphertext: odd number of ADFGVX letters." );
85+ }
86+
8387 StringBuilder plaintext = new StringBuilder ();
8488 for (int i = 0 ; i < fractionatedText .length (); i += 2 ) {
8589 String pair = fractionatedText .substring (i , i + 2 );
86- plaintext .append (POLYBIUS_MAP .get (pair ));
90+ Character letter = POLYBIUS_MAP .get (pair );
91+ if (letter == null ) {
92+ throw new IllegalArgumentException ("Invalid ciphertext: unknown ADFGVX pair \" " + pair + "\" ." );
93+ }
94+ plaintext .append (letter );
8795 }
8896
8997 return plaintext .toString ();
@@ -110,11 +118,7 @@ private String columnarTransposition(String text, String key) {
110118
111119 // Read columns based on the alphabetical order of the key
112120 StringBuilder ciphertext = new StringBuilder ();
113- char [] sortedKey = key .toCharArray ();
114- Arrays .sort (sortedKey );
115-
116- for (char keyChar : sortedKey ) {
117- int column = key .indexOf (keyChar );
121+ for (int column : columnsInKeyOrder (key )) {
118122 for (char [] row : table ) {
119123 if (row [column ] != '_' ) {
120124 ciphertext .append (row [column ]);
@@ -125,6 +129,24 @@ private String columnarTransposition(String text, String key) {
125129 return ciphertext .toString ();
126130 }
127131
132+ /**
133+ * Returns the column indices in the order the key imposes: alphabetical by
134+ * key letter, with repeated letters ordered by their first occurrence.
135+ * Using key.indexOf for repeated letters would map both occurrences to the
136+ * same column and make the transposition lossy.
137+ */
138+ private int [] columnsInKeyOrder (String key ) {
139+ Integer [] order = new Integer [key .length ()];
140+ for (int i = 0 ; i < order .length ; i ++) {
141+ order [i ] = i ;
142+ }
143+ Arrays .sort (order , (a , b ) -> {
144+ int byLetter = Character .compare (key .charAt (a ), key .charAt (b ));
145+ return byLetter != 0 ? byLetter : Integer .compare (a , b );
146+ });
147+ return Arrays .stream (order ).mapToInt (Integer ::intValue ).toArray ();
148+ }
149+
128150 /**
129151 * Helper method: Reverses the columnar transposition during decryption
130152 *
@@ -133,31 +155,36 @@ private String columnarTransposition(String text, String key) {
133155 * @return The reversed text
134156 */
135157 private String reverseColumnarTransposition (String ciphertext , String key ) {
136- int numRows = (int ) Math .ceil ((double ) ciphertext .length () / key .length ());
137- char [][] table = new char [numRows ][key .length ()];
158+ int numCols = key .length ();
159+ int fullRows = ciphertext .length () / numCols ;
160+ int remainder = ciphertext .length () % numCols ;
161+ // The last row of the encryption table is only partially filled: the
162+ // first `remainder` columns hold one extra character. The previous
163+ // implementation assumed every column had the same length, which
164+ // misaligned the whole grid whenever the length was not a multiple of
165+ // the key length.
166+ int [] columnLength = new int [numCols ];
167+ for (int column = 0 ; column < numCols ; column ++) {
168+ columnLength [column ] = fullRows + (column < remainder ? 1 : 0 );
169+ }
138170
139- char [] sortedKey = key . toCharArray ( );
140- Arrays . sort ( sortedKey ) ;
171+ int numRows = fullRows + ( remainder > 0 ? 1 : 0 );
172+ char [][] table = new char [ numRows ][ numCols ] ;
141173
142174 int index = 0 ;
143175 // Populate the table column by column according to the sorted key
144- for (char keyChar : sortedKey ) {
145- int column = key .indexOf (keyChar );
146- for (int row = 0 ; row < numRows ; row ++) {
147- if (index < ciphertext .length ()) {
148- table [row ][column ] = ciphertext .charAt (index ++);
149- } else {
150- table [row ][column ] = '_' ;
151- }
176+ for (int column : columnsInKeyOrder (key )) {
177+ for (int row = 0 ; row < columnLength [column ]; row ++) {
178+ table [row ][column ] = ciphertext .charAt (index ++);
152179 }
153180 }
154181
155182 // Read the table row by row to reconstruct the fractionated text
156183 StringBuilder fractionatedText = new StringBuilder ();
157- for (char [] row : table ) {
158- for (char cell : row ) {
159- if (cell != '_' ) {
160- fractionatedText .append (cell );
184+ for (int row = 0 ; row < numRows ; row ++ ) {
185+ for (int column = 0 ; column < numCols ; column ++ ) {
186+ if (row < columnLength [ column ] ) {
187+ fractionatedText .append (table [ row ][ column ] );
161188 }
162189 }
163190 }
0 commit comments