• Articles
  • Tutorials
  • Interview Questions

Playfair Cipher with Examples and Rules

What is Playfair Cipher?

The Playfair Cipher encryption technique can be used to encrypt or encode a message. It operates exactly like typical encryption. The only difference is that it encrypts a digraph, or a pair of two letters, instead of a single letter.

An initial 5×5 matrix key table is created. The plaintext encryption key is made out of the matrix’s alphabetic characters. Be mindful that you shouldn’t repeat the letters. There are 26 alphabets however, there are only 25 spaces in which we can place a letter. The matrix will delete the extra letter because there is an excess of one letter (typically J). Despite this, J is there in the plaintext before being changed to I.

This blog provides a full explanation of the Playfair Cipher, its advantages and disadvantages, its applicability, and the Playfair encryption and decryption algorithms.

Check out our free Cyber Security Course on our YouTube Channel and start learning today!

History of Playfair Cipher

The Playfair Cipher is the earliest and best-known digraph substitution cipher to use symmetry encryption. Charles Wheatstone developed the cipher in 1854, and Lord Playfair, who supported its use, gave it its name. In contrast to a simple substitution cipher, which simply encrypts single letters, the Playfair Cipher technique encrypts digraphs or parts of letters.

The Playfair Cipher is rapid and doesn’t require any additional tools to use. British forces employed it tactically in World War I, the Second Boer War, and World War II, as did Australian forces. The major goal of the encryption was to safeguard non-critical yet important information during actual combat. By the time the opposition’s cryptanalysts were able to decrypt it, the data was useless.

If you want to learn more and make a career in the field of Cyber Security, make sure to check out Cyber Security Course.

Get Familiar with the Terminologies

Get familiar with the Terminologies
  • Plaintext: The entire conversation must be encrypted. It’s also referred to as a message. It is an encrypted or ciphertext message.
  • The cipher algorithm converts plaintext into ciphertext, which serves as the decryption or encryption key for text. Only the sender and the recipient are aware of it. The key table or key-matrix is filled in character by character.
  • Enciphering is the process of converting plaintext into ciphertext.
  • Deciphering is the process of separating plaintext from ciphertext.
  • Cryptanalysis is the study of non-key decoding algorithms and concepts for ciphertext.

Get a deep understanding of the Access Control List through this blog!

Playfair Cipher’s Advantages:

  • If we carefully study the algorithm, we can see that each stage of the process results in a distinct ciphertext, which makes it more challenging for the cryptanalyst.
  • Brute force attacks do not affect it.
  • Cryptanalysis is not possible (decode a cipher without knowing the key).
  • eliminates the flaw in the simple Playfair square cipher.
  • Making the substitution is easy.

EPGC in Cyber Security and Ethical Hacking

Playfair Cipher Restrictions:

The Playfair Cipher is constrained by the following:

  • Only 25 alphabets are supported.
  • It is incompatible with characters that number.
  • Only capital or lowercase letters are accepted.
  • Special characters like spaces, newlines, punctuation, etc. are not allowed.

Interested in knowing what is google hacking, then do check out our blog on Google Dorking!

Importance of the Playfair Cipher

Due to its relative complexity compared to other ciphers at the time, during World Wars I and II, the Playfair Cipher became very well known. Furthermore, neither the encryption nor the decryption of the data required any specialized tools or methods. However, with the advent of computers, the Playfair Cipher was no longer used since computers could easily apply break codes to decrypt Playfair Ciphers.

As a result, with the advancement of digital encryption and the passage of time, the Playfair Cipher was no longer a feasible form of message encoding due to the possibility of data getting into the wrong hands. Therefore, using the Playfair Cipher for corporate enterprises is not recommended.

Looking for a rewarding career in ethical hacking? Enroll in our Ethical Hacking course and pave the way for success.

Ancient Cryptographic Systems

Ancient Cryptographic Systems

All previous cryptographic systems, or “ciphers,” were built on the principle of symmetric key encryption. Unlike modern digital systems, which process data as binary numbers, they worked using alphabets as the essential building blocks. One of the earliest cryptographic systems is the Playfair cipher, listed below.

Caesar’s Cipher

The Caesar cipher, commonly referred to as the Shift cipher, is the most basic type of substitution cipher scheme. By substituting a new letter for each letter in the plaintext alphabet that is displaced by a set number between 0 and 25, one can use this cipher to construct ciphertext. Because there are only 26 possible keys to decrypt the plaintext, it is an unsafe cryptosystem that a small-scale attacker can exploit.

Cipher using Simple Substitution

This encryption technique relies on utilizing different permutations of alphabetic letters. With 26 possible choices for each letter, there are 26! (26 factorial) potential permutations, resulting in a ciphertext alphabet with 4 x 10^26 possible combinations. This vast number of permutations forms the secret key of the cipher. However, despite the large number of keys that current computer machines cannot feasibly break, the cipher is susceptible to design flaws, such as the selection of an easily recognizable permutation. Consequently, the cipher is considered insecure.

Cipher Vigenere

 The key for the Vigenere cipher is a text string. The plaintext’s alphabets are shifted by converting each alphabet in the key to its corresponding numeric value. Since the Caesar cipher was modified to create this cipher, the cryptosystem is more robust.

Upgrade your cybersecurity skills with our Ethical Hacking course in Chennai. Join us and secure the digital realm!

Get 100% Hike!

Master Most in Demand Skills Now !

Encryption rules: Playfair Cipher

  • Split the plaintext first into digraphs (pairs of two letters). If the plaintext has an odd number of letters, append the letter Z at the end. Even the text in the basic form of The MANGO plaintext, for instance, consists of five letters. Consequently, it is not possible to make a digraph. As a result, we will change the plaintext to MANGOZ by adding the letter Z at the end.
  • Divide the plaintext into digraphs after that (pair of two letters). For any letter that appears twice, place an X there (side by side). Think about the scenario where the digraph is CO MX MU NI CA TE and the plaintext is COMMUNICATE. For plaintext GREET, the digraph will be GR EX ET, but for plaintext JAZZ, the digraph will be JA ZX ZX.
  • To identify the cipher (encryption) text, create a 5*5 key-matrix or key-table and fill it with alphabetic letters as follows:
  1. The first row, from left to right, should include the letters for the supplied keyword (ATHENS). If there are any duplicate letters in a keyword, avoid using them. This means a letter will only be taken into account once. Fill in the remaining letters alphabetically after that. Let’s create a 5*5 key-matrix for the keyword ATHENS.

Remember that there are no duplicate letters in the above matrix. The first row of letters (in green) stands in for the keyword, while the remaining letter sets are organized alphabetically.

The following three scenarios are conceivable:

i) If two letters occur together in a row as a digraph, Each letter in the digraph, in this case, should be replaced with the letter that is immediate to its right. If there is no letter to the right, the first letter in the same row is considered to be the right letter. Assuming Z is a letter for which the appropriate letter is required, T will be the appropriate letter in this situation.

ii) If a pair of letters (digraph) appears in the same column

In this case, replace each letter of the digraph with the letters immediately below them. If there is no letter below, wrap around to the top of the same column. Suppose, W is a letter whose below letter is required, in such case, V will be below W.

iii) In the event that a digraph (a pair of letters) is present in both its corresponding row and column:

To generate a cipher for a pair of letters within a 33 matrix, a 33 subset is selected from a larger 5*5 matrix. Specifically, two square corners within the matrix are chosen, which are positioned on opposite sides of a square. The remaining corner serves as the substitution for the given digraph.

In simpler terms, the cipher for the first letter will be the intersection of the letters H and Y.

Let’s consider the scenario where we need to create a cipher for the digraph HY. As observed, both H and Y are situated in different rows and columns.

Looking for jobs in the field? Top 50 Cyber Security Interview Questions is a great kickstart to achieve it.

Decryption rules: Playfair Cipher

Decryption procedures are used in reverse order as encryption procedures. When decrypting, the cipher is symmetric (move left along rows and up along columns). The same key and key table that are used to decode the message are accessible to the recipient of plain text.

Let’s see an example of a Playfair Cipher.

Playfair Cipher example

Assume “communication” is the plaintext and “computer” is the encryption key.

The key might be any word or phrase. Let’s figure out what was communicated.

1. First, create a digraph from the plaintext by applying rule 2, which is CO MX MU NI CA TE.

2.  Make a key matrix that is 5 by 5. (by rule 3). The significant element in our circumstances is the computer.3. We will now look through each key-matrix pair individually to find the corresponding encipher.

3. We will now look through each key-matrix pair individually to find the corresponding encipher.

  • The first digraph is CO. The two are displayed together in a row. The CO and OM are encrypted using Rule 4(i).
  • The second digraph is MX. Both of them are visible in the same column. The MX and RM are encrypted using Rule 4(ii).
  • The third digraph is MU. The two are displayed together in a row. MU is encrypted into the PC using Rule 4(i).
  • The fourth digraph is NI. The pair is visible in several rows and columns. NI is encrypted into SG using Rule 4(iii).
  • The sixth digraph is CA. The pair is visible in several rows and columns. Rule 4(iii) states are used by CA to encrypt data.
  • Therefore, the plaintext COMMUNICATE is encrypted using OMRMPCSGPTER.

Get interview-ready with our collection of Ethical Hacking Interview Questions. Equip yourself with the knowledge to impress potential employers!

Code Implementation

import java.awt.Point;  
import java.util.Scanner;  
public class PlayfairCipher  
{  
//length of digraph array  
private int length = 0;  
//creates a matrix for Playfair cipher   
private String [][] table;  
//main() method to test Playfair method  
public static void main(String args[])  
{  
PlayfairCipher pf = new PlayfairCipher();  
}  
//main run of the program, Playfair method  
//constructor of the class  
private PlayfairCipher()  
{  
//prompts the user for the keyword to use for encoding & creates tables  
System.out.print("Enter the key for Playfair cipher: ");  
Scanner sc = new Scanner(System.in);  
String key = parseString(sc);  
while(key.equals(""))  
key = parseString(sc);  
table = this.cipherTable(key);  
//prompts the user for the message to be encoded  
System.out.print("Enter the plaintext to be enciphered: ");  
//System.out.println("using the previously given keyword");  
String input = parseString(sc);  
while(input.equals(""))  
input = parseString(sc);  
//encodes and then decodes the encoded message  
String output = cipher(input);  
String decodedOutput = decode(output);  
//output the results to a user  
this.keyTable(table);  
this.printResults(output,decodedOutput);  
}  
//parses an input string to remove numbers, punctuation,  
//replaces any J's with I's and makes string all caps  
private String parseString(Scanner sc)  
{  
String parse = sc.nextLine();  
//converts all the letters in upper case  
parse = parse.toUpperCase();  
//the string to be substituted by space for each match (A to Z)  
parse = parse.replaceAll("[^A-Z]", "");  
//replace the letter J by I  
parse = parse.replace("J", "I");  
return parse;  
}  
//creates the cipher table based on some input string (already parsed)  
private String[][] cipherTable(String key)  
{  
//creates a matrix of 5*5     
String[][] playfairTable = new String[5][5];  
String keyString = key + "ABCDEFGHIKLMNOPQRSTUVWXYZ";  
//fill string array with the empty string  
for(int i = 0; i < 5; i++)  
for(int j = 0; j < 5; j++)  
playfairTable[i][j] = "";  
for(int k = 0; k < keyString.length(); k++)  
{  
boolean repeat = false;  
boolean used = false;  
for(int i = 0; i < 5; i++)  
{  
for(int j = 0; j < 5; j++)  
{  
if(playfairTable[i][j].equals("" + keyString.charAt(k)))  
{  
repeat = true;  
}  
else if(playfairTable[i][j].equals("") && !repeat && !used)  
{  
playfairTable[i][j] = "" + keyString.charAt(k);  
used = true;  
}  
}  
}  
}  
return playfairTable;  
}  
//cipher: takes input (all upper-case), encodes it, and returns the output  
private String cipher(String in)  
{  
length = (int) in.length() / 2 + in.length() % 2;  
//insert x between double-letter digraphs & redefines "length"  
  
for(int i = 0; i < (length - 1); i++)  
{  
if(in.charAt(2 * i) == in.charAt(2 * i + 1))  
{  
in = new StringBuffer(in).insert(2 * i + 1, 'X').toString();  
length = (int) in.length() / 2 + in.length() % 2;  
}  
}  
//------------makes plaintext of even length--------------  
//creates an array of digraphs  
String[] digraph = new String[length];  
//loop iterates over the plaintext  
for(int j = 0; j < length ; j++)  
{  
//checks whether the plaintext is of even length or not   
if(j == (length - 1) && in.length() / 2 == (length - 1))  
//if not addends X at the end of the plaintext    
in = in + "X";  
digraph[j] = in.charAt(2 * j) +""+ in.charAt(2 * j + 1);  
}  
//encodes the digraphs and returns the output  
String out = "";  
String[] encDigraphs = new String[length];  
encDigraphs = encodeDigraph(digraph);  
for(int k = 0; k < length; k++)  
out = out + encDigraphs[k];  
return out;  
}  
//---------------encryption logic-----------------  
//encodes the digraph input with the cipher's specifications  
private String[] encodeDigraph(String di[])  
{  
String[] encipher = new String[length];  
for(int i = 0; i < length; i++)  
{  
char a = di[i].charAt(0);  
char b = di[i].charAt(1);  
int r1 = (int) getPoint(a).getX();  
int r2 = (int) getPoint(b).getX();  
int c1 = (int) getPoint(a).getY();  
int c2 = (int) getPoint(b).getY();  
//executes if the letters of digraph appear in the same row  
//in such case shift columns to right  
if(r1 == r2)  
{  
c1 = (c1 + 1) % 5;  
c2 = (c2 + 1) % 5;  
}  
//executes if the letters of digraph appear in the same column  
//in such case shift rows down  
else if(c1 == c2)  
{  
r1 = (r1 + 1) % 5;  
r2 = (r2 + 1) % 5;  
}  
//executes if the letters of digraph appear in the different rows and different column  
//in such case swap the first column with the second column  
else  
{  
int temp = c1;  
c1 = c2;  
c2 = temp;  
}  
//performs the table look-up and puts those values into the encoded array  
encipher[i] = table[r1][c1] + "" + table[r2][c2];  
}  
return encipher;  
}  
//-----------------------decryption logic---------------------  
// decodes the output given from the cipher and decode methods (opp. of encoding process)  
private String decode(String out)  
{  
String decoded = "";  
for(int i = 0; i < out.length() / 2; i++)  
{  
char a = out.charAt(2*i);  
char b = out.charAt(2*i+1);  
int r1 = (int) getPoint(a).getX();  
int r2 = (int) getPoint(b).getX();  
int c1 = (int) getPoint(a).getY();  
int c2 = (int) getPoint(b).getY();  
if(r1 == r2)  
{  
c1 = (c1 + 4) % 5;  
c2 = (c2 + 4) % 5;  
}  
else if(c1 == c2)  
{  
r1 = (r1 + 4) % 5;  
r2 = (r2 + 4) % 5;  
}  
else  
{  
//swapping logic      
int temp = c1;  
c1 = c2;  
c2 = temp;  
}  
decoded = decoded + table[r1][c1] + table[r2][c2];  
}  
//returns the decoded message  
return decoded;  
}  
// returns a point containing the row and column of the letter  
private Point getPoint(char c)  
{  
Point pt = new Point(0,0);  
for(int i = 0; i < 5; i++)  
for(int j = 0; j < 5; j++)  
if(c == table[i][j].charAt(0))  
pt = new Point(i,j);  
return pt;  
}  
//function prints the key-table in matrix form for Playfair cipher  
private void keyTable(String[][] printTable)  
{  
System.out.println("Playfair Cipher Key Matrix: ");  
System.out.println();  
//loop iterates for rows  
for(int i = 0; i < 5; i++)  
{  
//loop iterates for column    
for(int j = 0; j < 5; j++)  
{  
//prints the key-table in matrix form     
System.out.print(printTable[i][j]+" ");  
}  
System.out.println();  
}  
System.out.println();  
}    
//method that prints all the results  
private void printResults(String encipher, String dec)  
{  
System.out.print("Encrypted Message: ");  
//prints the encrypted message  
System.out.println(encipher);  
System.out.println();  
System.out.print("Decrypted Message: ");  
//prints the decrypted message  
System.out.println(dec);  
}  
}  

OUTPUT:

Conclusion

The Playfair Cipher is recognized as one of the oldest and most effective techniques for data encryption. A solid understanding of the Playfair Cipher serves as a foundational element for data encryption and machine learning.

Do you intend to pursue a career in cyber security now? For more assistance, please visit our Cyber Security Community!

Course Schedule

Name Date Details
Cyber Security Course 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Cyber Security Course 04 May 2024(Sat-Sun) Weekend Batch
View Details
Cyber Security Course 11 May 2024(Sat-Sun) Weekend Batch
View Details