1+ package com .thealgorithms .ciphers ;
2+
3+ /**
4+ * A Java implementation of Polybius Cipher
5+ * Polybius is a substitution cipher method
6+ * It was invented by a greek philosopher that name is Polybius
7+ * Letters in alphabet takes place to two dimension table.
8+ * Encrypted text is created according to row and column in two dimension table
9+ * Decrypted text is generated by looking at the row and column respectively
10+ * Additionally, some letters in english alphabet deliberately throws such as U because U is very similar with V
11+ *
12+ * @author Hikmet ÇAKIR
13+ * @since 08-07-2022+03:00
14+ */
15+ public class Polybius {
16+
17+ private static final char [][] key = {
18+ // 0 1 2 3 4
19+ /* 0 */ {'A' , 'B' , 'C' , 'D' , 'E' },
20+ /* 1 */ {'F' , 'G' , 'H' , 'I' , 'J' },
21+ /* 2 */ {'K' , 'L' , 'M' , 'N' , 'O' },
22+ /* 3 */ {'P' , 'Q' , 'R' , 'S' , 'T' },
23+ /* 4 */ {'V' , 'W' , 'X' , 'Y' , 'Z' }
24+ };
25+
26+ private static String findLocationByCharacter (final char character ) {
27+ final StringBuilder location = new StringBuilder ();
28+ for (int i = 0 ; i < key .length ; i ++) {
29+ for (int j = 0 ; j < key [i ].length ; j ++) {
30+ if (character == key [i ][j ]) {
31+ location .append (i ).append (j );
32+ break ;
33+ }
34+ }
35+ }
36+ return location .toString ();
37+ }
38+
39+ public static String encrypt (final String plaintext ) {
40+ final char [] chars = plaintext .toUpperCase ().toCharArray ();
41+ final StringBuilder ciphertext = new StringBuilder ();
42+ for (char aChar : chars ) {
43+ String location = findLocationByCharacter (aChar );
44+ ciphertext .append (location );
45+ }
46+ return ciphertext .toString ();
47+ }
48+
49+ public static String decrypt (final String ciphertext ) {
50+ final char [] chars = ciphertext .toCharArray ();
51+ final StringBuilder plaintext = new StringBuilder ();
52+ for (int i = 0 ; i < chars .length ; i +=2 ) {
53+ int pozitionX = Character .getNumericValue (chars [i ]);
54+ int pozitionY = Character .getNumericValue (chars [i + 1 ]);
55+ plaintext .append (key [pozitionX ][pozitionY ]);
56+ }
57+ return plaintext .toString ();
58+ }
59+ }
0 commit comments