Ins 3
Ins 3
Ins 3
Introduction: 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 employs a table where one letter
of the alphabet is omitted, and the letters are arranged in a 5x5 grid. Typically, the J is
removed from the alphabet and an I takes its place in the text that is to be encoded.
Code:
Encryption:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
dicty['j' - 97] = 1;
i = 0;
j = 0;
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
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)
{
return (a % 5);
}
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]];
}
}
}
ks = strlen(key);
ks = removeSpaces(key, ks);
toLowerCase(key, ks);
ps = strlen(str);
toLowerCase(str, ps);
ps = removeSpaces(str, ps);
ps = prepare(str, ps);
int main()
{
char str[SIZE], key[SIZE];
strcpy(key, "Monarchy");
printf("Key text: %s\n", key);
strcpy(str, "instruments");
printf("Plain text: %s\n", str);
encryptByPlayfairCipher(str, key);
return 0;
}
Decryption:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
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;
}
}
}
}
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
int mod5(int a)
{
return (a % 5);
}
ks = strlen(key);
ks = removeSpaces(key, ks);
toLowerCase(key, ks);
ps = strlen(str);
toLowerCase(str, ps);
ps = removeSpaces(str, ps);
int main()
{
char str[SIZE], key[SIZE];
strcpy(key, "Monarchy");
printf("Key text: %s\n", key);
strcpy(str, "gatlmzclrqtx");
printf("Plain text: %s\n", str);
decryptByPlayfairCipher(str, key);
return 0;
}
Output:
Encryption:
Decryption: