Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Let's start the article with an interesting fact, Playfair cipher was invented by Charles Wheatstone in 1854 but named after his friend Lord Playfair. Why you may ask. It is named after Lord Playfair for promoting the use of the cipher.
Before diving deep into the Playfair cipher program in C, let’s first quickly understand what a cipher is. A cipher is an algorithm for encrypting and decrypting data in the study of cryptographic techniques, known as cryptology.
What is Playfair Cipher?
The Playfair Cipher Program in C is the first and the most well-known symmetric encryption digraph substitution cipher. When using symmetric encryption techniques, data is encrypted using the same key regardless of whether the goal is to transform plaintext into ciphertext or ciphertext into plaintext. A cipher alters data by converting the original plaintext characters or other data into ciphertext. The Playfair Cipher Program in C approach encrypts digraphs or sections of letters instead of a standard substitution cipher, which only encrypts single letters. it encrypts a digraph or a pair of two letters.
Encryption Technique
A message goes through some intermediate channels between the time it is sent by the sender and the time it is received by the receiver. These channels are crucial for message transmission. There is a possibility that the message could be hacked mid-transmission. Therefore, "Encryption Techniques" are used to protect this communication and ensure that it is delivered without any interference. The Playfair cipher is a classic symmetric encryption technique that uses a 5x5 matrix of letters to encrypt plaintext messages.
Playfair Cipher Encryption Algorithm
The two stages of the Playfair Cipher technique are listed below. In this method, some factors are predetermined while others must be discovered. For instance, the factors include the message, which is the "plain-text" that needs to be transformed into the cypher-text, and the "keyword" that needs to be entered into the 5*5 matrix structure.
Generate the Key Square(5×5): We must first create a square box with a 5 by 5 grid in which to put the keyword. This text box serves as the encryption secret for the plain text that will be entered next. Each box in this key is filled with letters. The letters should all be distinct. Since the key square can only hold 25 characters, the letter "J" is typically removed. However, if "J" is already present in plain text, "I" is used.
Algorithm to Encrypt the Plain Text: The plain text that needs to be encrypted is divided into letter pairs by an algorithm. (digraphs). If the amount of letters after splitting the plain text is odd, a "Z" is added to the final letter. Additionally, each letter in a combination should be distinct. All the unique letters from left to right of the Keyword are filled in the grid and then the remainder grids are filled with the remaining letters of alphabet. We have "Chipher," for instance, in simple text. It will be after dividing that: ( Ch, ip, he, and rz).
Terminology
Playfair Cipher: A manual symmetric encryption technique that encrypts pairs of letters (digraphs) instead of single letters, invented by Charles Wheatstone.
Key Matrix: A 5x5 grid of letters used for encryption and decryption in the Playfair cipher, generated using a keyword.
Keyword: A word or phrase used to fill the key matrix, omitting duplicate letters and typically combining 'I' and 'J'.
Digraph: A pair of letters encrypted together in the Playfair cipher.
Encryption: The process of converting plaintext into ciphertext using the key matrix.
Decryption: The process of converting ciphertext back into plaintext using the key matrix.
Plaintext: The original message that needs to be encrypted.
Ciphertext: The encrypted message produced by the cipher.
Row Rule: If both letters in the digraph are in the same row of the key matrix, each letter is replaced by the letter immediately to its right.
Column Rule: If both letters in the digraph are in the same column of the key matrix, each letter is replaced by the letter immediately below it.
Rectangle Rule: If the letters form a rectangle, each letter is replaced by the letter in its row but in the column of the other letter of the pair.
Padding: Adding a filler letter (commonly 'X') between repeated letters in a digraph or at the end of the plaintext to form complete digraphs.
Preprocessing: Steps taken before encryption, such as removing spaces and converting all letters to uppercase.
Postprocessing: Steps taken after decryption to format the plaintext, such as removing padding letters.
Symmetric Encryption: A type of encryption where the same key is used for both encryption and decryption.
Playfair Cipher Rules for Encryption
The rules of encrypting Playfair cipher can be simply summarized as follows:
After making the pair of the plaintext, if the digraph comes in the same column, we have to take the element just below the letters. Example: The digraph is 'ZN', then the encrypted text will be ' GS'.
After making the pair the, if the digraph is coming in the same row, we have to take the rightmost element of the pair. Example: The digraph is 'OP', then the encrypted text will be 'PQ'.
If neither of the above criteria is met, simply draw an imaginary rectangle using the positions of these two letters as the rectangle's diagonal and then swap the letters with another diagonal letter. Example: The digraph is 'NQ', then the encrypted text will be 'OA'.
Implementation of Playfair Cipher in C
Here is the Playfair cipher program in C; In this program, we will pass a key text and our plaintext, which will be encrypted by the program.
// Playfair Cipher Program in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Function for Playfair Cipher encryption */
void Playfair(char str[], char keystr[]) {
char keyMat[5][5];
// Key & plainText
char ks = strlen(keystr);
char ps = strlen(str);
void toUpperCase(char encrypt[], int ps) {
for (int i= 0; i < ps; i++) {
if (encrypt[i] > 96 && encrypt[i] < 123)
encrypt[i] -= 32;
}
}
int removeSpaces(char* plain, int ps) {
int i, count = 0;
for (i = 0; i < ps; i++)
if (plain[i] != ' ')
plain[count++] = plain[i];
plain[count] = '\0';
return count;
}
/* this function will create a 5 by 5 matrix. */
void createMatrix(char keystr[], int ks, char keyMat[5][5]) {
int flag = 0, *dict;
/* here we are creating a hashmap for alphabets */
dict = (int*)calloc(26, sizeof(int));
for (int i = 0; i < ks; i++) {
if (keystr[i] != 'j')
dict[keystr[i] - 97] = 2;
}
dict['j' - 97] = 1;
int i = 0, j = 0;
for (int k = 0; k < ks; k++) {
if (dict[keystr[k] - 97] == 2) {
dict[keystr[k] - 97] -= 1;
keyMat[i][j] = keystr[k];
j++;
if (j == 5) {
i++;
j = 0;
}
}
}
for (int k = 0; k < 26; k++) {
if (dict[k] == 0) {
keyMat[i][j] = (char)(k + 97);
j++;
if (j == 5) {
i++;
j = 0;
}
}
}
}
/*this function looks for a digraph's characters in the key matrix and returns their positions.*/
void search(char keyMat[5][5], char a, char b, int arr[]) {
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 (keyMat[i][j] == a) {
arr[0] = i;
arr[1] = j;
}
else if (keyMat[i][j] == b) {
arr[2] = i;
arr[3] = j;
}
}
}
}
/* This function avoids duplication and levels out the length of plain text by making it even.*/
int prep(char str[], int p) {
int sub = p;
for (int i = 0; i < sub; i += 2) {
if(str[i]==str[i+1]){
for(int j=sub; j>i+1; j--){
str[j]=str[j-1];
}
str[i+1]='x';
sub+=1;
}
}
str[sub]='\0';
if (sub % 2 != 0) {
str[sub++] = 'z';
str[sub] = '\0';
}
return sub;
}
// Here, the encryption is done.
void encrypt(char str[], char keyMat[5][5], int pos) {
int a[4];
for(int i=0; i<pos; i+=2){
search(keyMat, str[i], str[i + 1], a);
if (a[0] == a[2]) {
str[i] = keyMat[a[0]][(a[1] + 1)%5];
str[i + 1] = keyMat[a[0]][(a[3] + 1)%5];
}
else if (a[1] == a[3]) {
str[i] = keyMat[(a[0] + 1)%5][a[1]];
str[i + 1] = keyMat[(a[2] + 1)%5][a[1]];
}
else {
str[i] = keyMat[a[0]][a[3]];
str[i + 1] = keyMat[a[2]][a[1]];
}
}
}
ks = removeSpaces(keystr, ks);
ps = removeSpaces(str, ps);
ps = prep(str, ps);
createMatrix(keystr, ks, keyMat);
encrypt(str, keyMat, ps);
toUpperCase(str, ps);
/* str is the final encrypted string in uppercase */
printf("Cipher text: %s\n", str);
}
int main() {
char string[200], keyString[200];
printf("Enter key: ");
scanf("%[^\n]s", &keyString);
printf("Enter plaintext: ");
scanf("\n");
scanf("%[^\n]s", &string);
//Playfair Cipher Program in C functional call
Playfair(string, keyString);
return 0;
}
Output:
Decryption Technique
The same steps used for encryption are used in reverse sequence for decrypting the messages. The key will be the same for encryption and decoding because this is a symmetrical encryption method, as is well known. The recipient performs the decryption.
Playfair Cipher Decryption Algorithm
Again the decryption will be done in the following two algorithms:
Generate the key Square(5×5) at the Receiver’s End: The square, which will be of order 5*5, will be filled in one character at a time. The text box's alphabet should all be entirely distinct. The character "J" is typically removed from the box because there are only 25 squares in the grid, and there are 26 letters in the alphabet. The character "J" is changed to "I" in the square box if it appears in the cipher text. The boxes are initially filled with all of the individual characters from the key from left to right. The letters of the alphabet appear in the sequence of the alphabet.
Decrypt the Ciphertext: The ciphertext is divided into two characters, or "Digraphs," for encryption. A ciphertext's character count is always an even amount. The matching enciphers then search for each pair as the key matrices are then traversed pair by pair.
Playfair Cipher Rules for Decryption
After making the pair of the plaintext, if the digraph comes in the same column, we have to take the element just above the letters. Example: The digraph is 'GS', then the decrypted text will be ' ZN'.
After making the pair the, if the digraph is coming in the same row, we have to take the leftmost element of the pair. Example: The digraph is 'PQ', then the decrypted text will be 'OP'.
If neither of the above criteria is met, simply draw an imaginary rectangle using the positions of these two letters as the rectangle's diagonal and then swap the letters with another diagonal letter. Example: The digraph is ' QA' , then the decrypted text will be 'NQ'.
Implementation of Playfair Cipher Decryption in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
void change_to_lowercase(char plain[], int ps)
{
int i;
for (i = 0; i < ps; i++) {
if (plain[i] > 64 && plain[i] < 91)
plain[i] += 32;
}
}
int remove_all_spaces(char* plain, int ps)
{
int i, count = 0;
for (i = 0; i < ps; i++)
if (plain[i] != ' ')
plain[count++] = plain[i];
plain[count] = '\0';
return count;
}
void generate_key(char key[], int ks, char keyT[5][5])
{
int i, j, k, flag = 0, *dicty;
dicty = (int*)calloc(26, sizeof(int));
for (i = 0; i < ks; i++) {
if (key[i] != 'j')
dicty[key[i] - 97] = 2;
}
dicty['j' - 97] = 1;
i = 0;
j = 0;
for (k = 0; k < ks; k++) {
if (dicty[key[k] - 97] == 2) {
dicty[key[k] - 97] -= 1;
keyT[i][j] = key[k];
j++;
if (j == 5) {
i++;
j = 0;
}
}
}
for (k = 0; k < 26; k++) {
if (dicty[k] == 0) {
keyT[i][j] = (char)(k + 97);
j++;
if (j == 5) {
i++;
j = 0;
}
}
}
}
void searching(char keyT[5][5], char a, char b, int arr[])
{
int i, j;
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (keyT[i][j] == a) {
arr[0] = i;
arr[1] = j;
}
else if (keyT[i][j] == b) {
arr[2] = i;
arr[3] = j;
}
}
}
}
int mod5(int a)
{
if (a < 0)
a += 5;
return (a % 5);
}
void decrypt(char str[], char keyT[5][5], int ps)
{
int i, a[4];
for (i = 0; i < ps; i += 2) {
searching(keyT, str[i], str[i + 1], a);
if (a[0] == a[2]) {
str[i] = keyT[a[0]][mod5(a[1] - 1)];
str[i + 1] = keyT[a[0]][mod5(a[3] - 1)];
}
else if (a[1] == a[3]) {
str[i] = keyT[mod5(a[0] - 1)][a[1]];
str[i + 1] = keyT[mod5(a[2] - 1)][a[1]];
}
else {
str[i] = keyT[a[0]][a[3]];
str[i + 1] = keyT[a[2]][a[1]];
}
}
}
void decrypt_by_playfair_cipher(char str[], char key[])
{
char ps, ks, keyT[5][5];
// Key text
ks = strlen(key);
ks = remove_all_spaces(key, ks);
change_to_lowercase(key, ks);
// ciphertext
ps = strlen(str);
change_to_lowercase(str, ps);
ps = remove_all_spaces(str, ps);
generate_key(key, ks, keyT);
decrypt(str, keyT, ps);
}
int main()
{
char str[SIZE], key[SIZE];
strcpy(key, " wheatz");
printf("Key text: %s\n", key);
strcpy(str, " HTNF");
printf("Encrypted text: %s\n", str);
decrypt_by_playfair_cipher(str, key);
printf("Deciphered text: %s\n", str);
return 0;
}
The Playfair cipher is more secure than simple substitution ciphers because it uses a polygraphic substitution technique that combines multiple plaintext letters into a single ciphertext letter.
The cipher is also resistant to frequency analysis attacks because each letter is encrypted differently than in basic substitution ciphers, depending on its position in the plaintext.
It is a relatively fast encryption algorithm that can be easily implemented by hand or in software, making it perfect for low-resource devices or systems.
The use of a 5x5 grid of letters makes it simple to find the encryption key as well as encode and decode communications without the use of any special tools or equipment.
Disadvantages of Playfair Cipher
The Playfair cipher is susceptible to known-plaintext attacks, where an attacker can deduce parts of the key and use them to decrypt other messages encrypted with the same key.
The algorithm can be broken if the key is known or if the adversary can obtain enough ciphertexts encrypted with the same key to perform a frequency analysis attack.
The Playfair cipher is vulnerable to attacks based on the letter frequency of digrams, where the adversary can analyze the frequency of digrams in the ciphertext to deduce the plaintext or the key. This vulnerability can be reduced by adding padding or filler characters to the plaintext to disguise the frequency of digrams.
Frequently Asked Questions
Why is it called Playfair cipher?
Sir Charles Wheatstone created the "Playfair" cipher, and it was given this name in honor of his friend Lyon Playfair, the first Baron Playfair of St. Andrews, who popularized and promoted the cipher.
What are the Playfair cipher's rules?
When two letters are in different rows and columns, one of them is substituted for the other by the letter in the opposite row and column.
What type of cipher is Playfair?
Playfair cipher program is a block cipher that replaces a certain plaintext character with a ciphertext character partially determined by a neighboring plaintext character.
What does the cipher technique mean?
Any technique used to change a message to hide its true meaning is a cipher. The phrase can also refer to the message's encrypted form interchangeably with ciphertext or cryptogram.
How to decode Playfair cipher? Answer it in 20-25 words to the point. How many keys are there in the Playfair cipher? Answer it in 20-25 words to the point.
How to decode Playfair cipher?
To decode a Playfair cipher, apply the reverse rules: use the letter to the left or above in the key matrix, or swap columns.
How many keys are there in the Playfair cipher?
The Playfair cipher uses a single key, typically a keyword, to generate the 5x5 key matrix for both encryption and decryption.
Conclusion
This article covers everything you need to know about the Playfair Cipher Program in C. We hope this article on the Playfair Cipher Program in C helps you in your journey.