Java Program to Implement Playfair Cipher Algorithm Last Updated : 08 Dec, 2022 Comments Improve Suggest changes Like Article Like Report Cipher is an algorithm for encryption and decryption. The cipher text is a process that applies to different types of algorithms to convert plain text to coded text. It is referred to as ciphertext. The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In Playfair cipher unlike traditional cipher, we encrypt a pair of alphabets(digraphs) instead of a single alphabet. It was used for tactical purposes by British forces in the Second Boer War and in World War I and for the same purpose by the Australians during World War II. This was because Playfair is reasonably fast to use and requires no special equipment. Algorithm: Create a matrix of 5 cross 5 is made in which all the alphabet of English letters is placed in it. Now, you must be wondering that there are 26 alphabets while the matrix is only having 25 cells. To resolve it alphabets 'i' and 'j' are placed into a single cell.Now insert the key and put the remaining alphabets in the matrix. The matrix is made by inserting the value of the key and remaining alphabets into the matrix row-wise from left to right.Convert the text into pairs of alphabets keeping in mind no two alphabets should repeat consecutively. For example: 'code' is written as 'co','de'If the letter is repeating then add 'x' to make as many pair sets as many times the alphabet is repeating. For example: 'helloh' is written as 'he' 'lx', 'lx', 'oh'. Here letter 'l' was consecutive for 2 times hence two sets and two additions of 'x''sNow if after breakdown into pairs, a letter is left alone add 'z' to the letter just like we have added 'x'. For example: 'hello' is written as 'he' 'lx', 'lx', 'oz'Solve the matrix or forming code using 3 standard rulesIf both the alphabet are in the same row, replace them with alphabets to their immediate right.If both the alphabets are in the same column, replace them with alphabets immediately below them.If not in the same row or column, replace them with alphabets in the same row respectively, but at other pair of corners Illustration: codeufstkglrmnpei/jahbvwxyz Implementation: Generate the key Square(5×5)Encrypt the Plaintext Example Java // Java Program for Playfair Cipher Algorithm // Importing all utility classes import java.util.*; // Main class public class Main { // Removing the duplicate values from the key static String removeDuplicate(String s) { int j, index = 0, len = s.length(); char c[] = s.toCharArray(); for (int i = 0; i < len; i++) { for (j = 0; j < i; j++) { if (c[i] == c[j]) break; } if (i == j) c[index++] = c[i]; } s = new String((Arrays.copyOf(c, index))); return s; } // Method 1 // Removing the white spaces from string 'st' // which was replaced by the key as space. static String removeWhiteSpace(char[] ch, String key) { char[] c = key.toCharArray(); // removing character which are input by the user // from string st for (int i = 0; i < c.length; i++) { for (int j = 0; j < ch.length; j++) { if (c[i] == ch[j]) c[i] = ' '; } } key = new String(c); key = key.replaceAll(" ", ""); return key; } // Method 2 // To make the pair for encryption in plaintext. static String makePair(String pt) { String s = ""; char c = 'a'; for (int i = 0; i < pt.length(); i++) { if (pt.charAt(i) == ' ') continue; else { c = pt.charAt(i); s += pt.charAt(i); } if (i < pt.length() - 1) if (pt.charAt(i) == pt.charAt(i + 1)) s += "x"; } // If plain text length is odd then // adding x to make length even. if (s.length() % 2 != 0) s += "x"; System.out.println(s); return s; } // Method 3 // To find the position of row and column in matrix // for encryption of the pair. static int[] findIJ(char a, char b, char x[][]) { int[] y = new int[4]; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (x[i][j] == a) { y[0] = i; y[1] = j; } else if (x[i][j] == b) { y[2] = i; y[3] = j; } } } if (y[0] == y[2]) { y[1] += 1; y[3] += 1; } else if (y[1] == y[3]) { y[0] += 1; y[2] += 1; } for (int i = 0; i < 4; i++) y[i] %= 5; return y; } // Method 4 // To encrypt the plaintext static String encrypt(String pt, char x[][]) { char ch[] = pt.toCharArray(); int a[] = new int[4]; for (int i = 0; i < pt.length(); i += 2) { if (i < pt.length() - 1) { a = findIJ(pt.charAt(i), pt.charAt(i + 1), x); if (a[0] == a[2]) { ch[i] = x[a[0]][a[1]]; ch[i + 1] = x[a[0]][a[3]]; } else if (a[1] == a[3]) { ch[i] = x[a[0]][a[1]]; ch[i + 1] = x[a[2]][a[1]]; } else { ch[i] = x[a[0]][a[3]]; ch[i + 1] = x[a[2]][a[1]]; } } } pt = new String(ch); return pt; } // Method 5 // Main driver method public static void main(String[] args) { // Creating an Scanner class object to // take input from user Scanner sc = new Scanner(System.in); String pt = "instruments"; // Key input String key = "monarchy"; key = removeDuplicate(key); char[] ch = key.toCharArray(); // Reading string array of Letters of english // alphabet as Playfair to implement String st = "abcdefghiklmnopqrstuvwxyz"; st = removeWhiteSpace(ch, st); char[] c = st.toCharArray(); // Matrix input using above key char[][] x = new char[5][5]; int indexOfSt = 0, indexOfKey = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (indexOfKey < key.length()) x[i][j] = ch[indexOfKey++]; else x[i][j] = c[indexOfSt++]; } } // Printing Matrix for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) System.out.print(x[i][j] + " "); System.out.println(); } // For getting encrypted output // Calling makePair() method over object created in // main() pt = makePair(pt); // Calling makePair() method over object created in // main() pt = encrypt(pt, x); // Print and display in the console System.out.println(pt); } } Outputm o n a r c h y b d e f g i k l p q s t u v w x z instrumentsx gatlmzclrqxa Create Quiz Comment R RitikKeshri Follow 0 Improve R RitikKeshri Follow 0 Improve Article Tags : Java Java Programs Explore Java BasicsIntroduction to Java3 min readJava Programming Basics9 min readJava Methods6 min readAccess Modifiers in Java4 min readArrays in Java7 min readJava Strings7 min readRegular Expressions in Java3 min readOOP & InterfacesClasses and Objects in Java5 min readAccess Modifiers in Java4 min readJava Constructors4 min readJava OOP(Object Oriented Programming) Concepts10 min readJava Packages2 min readJava Interface7 min readCollectionsCollections in Java12 min readCollections Class in Java13 min readCollection Interface in Java4 min readIterator in Java4 min readJava Comparator Interface5 min readException HandlingJava Exception Handling6 min readJava Try Catch Block4 min readJava final, finally and finalize4 min readChained Exceptions in Java3 min readNull Pointer Exception in Java5 min readException Handling with Method Overriding in Java4 min readJava AdvancedJava Multithreading Tutorial3 min readSynchronization in Java7 min readFile Handling in Java4 min readJava Method References7 min readJava 8 Stream Tutorial7 min readJava Networking6 min readJDBC Tutorial5 min readJava Memory Management3 min readGarbage Collection in Java6 min readMemory Leaks in Java3 min readPractice JavaJava Interview Questions and Answers1 min readJava Programs - Java Programming Examples7 min readJava Exercises - Basic to Advanced Java Practice Programs with Solutions5 min readJava Quiz1 min readJava Project Ideas For Beginners and Advanced15+ min read Like