C Source file of Program
#include<conio.h>
#include<stdio.h>
int flag[26];
void encryptingdecryptingText();
char* removeSpaces(char *pt)
{
int count=0;
int i=0;
int length=strlen(pt);
for(i=0;i<length;i++)
{
if(pt[i]!=' ')
pt[count++]=pt[i];
}
pt[count++]='\0';
return pt;
}
void main()
{
int i=0;
char *pt;
char *keyText;
clrscr();
for(i=0;i<26;i++)
{
flag[i]=-1;
}
pt="";
printf("Enter the plaintext to be encrypted\n");
gets(pt);
pt=removeSpaces(pt);
printf("Enter the key for the encryption\n");
gets(keyText);
encryptingdecryptingText(pt,keyText);
getch();
}
void encryptingdecryptingText(char *pt,char *keyText)
{
char play[5][5];
char *ct;
int ascii_value;
int rows=0,cols=0,i=0,j=0;
int row1=0,col1=0,row2=0,col2=0,r=0,c=0,av1=0,av2=0;
int length_key=strlen(keyText);
int length_of_pt=0;
strlwr(keyText);
for(i=0;i<length_key;i++)
{
ascii_value=(int)keyText[i]-97;
if(flag[ascii_value]==-1)
{
if(cols>=5)
{
cols=0;
play[++rows][cols++]=keyText[i];
r=rows;
c=cols-1;
}
else
{
play[rows][cols++]=keyText[i];
r=rows;
c=cols-1;
}
if(ascii_value==8||ascii_value==9)
{
flag[8]=(10*r)+c;
flag[9]=(10*r)+c;
}
else
flag[ascii_value]=(10*r)+c;
}
}
for(i=0;i<26;i++)
{
if(flag[i]==-1)
{
if(cols>=5)
{
cols=0;
play[++rows][cols++]=(char)(i+97);
r=rows;
c=cols-1;
}
else
{
play[rows][cols++]=(char)(i+97);
r=rows;
c=cols-1;
}
if(i==8||i==9)
{
flag[8]=(10*r)+c;
flag[9]=(10*r)+c;
}
else
flag[i]=(10*r)+c;
}
}
printf("PlayFair Key matrix\n");
for(i=0;i<5;i++)
{
printf("\t");
for(j=0;j<5;j++)
{
printf("%c",play[i][j]);
}
printf("\n");
}
printf("Plain text entered by you is %s \n",pt);
length_of_pt=strlen(pt);
for(i=0;i<length_of_pt-1;i++)
{
if(pt[i]==pt[i+1])
{
for(j=length_of_pt;j>i;j--)
{
pt[j+1]=pt[j];
}
pt[i+1]='x';
length_of_pt++;
}
}
if(length_of_pt%2!=0)
{
pt[length_of_pt]='x';
length_of_pt++;
}
pt[length_of_pt]='\0';
puts(pt);
for(i=0;i<length_of_pt;i+=2)
{
av1=(int)pt[i]-97;
av2=(int)pt[i+1]-97;
row1=flag[av1]/10;
col1=flag[av1]%10;
row2=flag[av2]/10;
col2=flag[av2]%10;
if(row1==row2)
{
ct[i]=(char)play[row1][(col1+1)%5];
ct[i+1]=(char)play[row1][(col2+1)%5];
}
else if(col1==col2)
{
ct[i]=(char)play[(row1+1)%5][col1];
ct[i+1]=(char)play[(row2+1)%5][col1];
}
else
{
ct[i]=(char)play[row1][col2];
ct[i+1]=(char)play[row2][col1];
}
}
ct[length_of_pt]='\0';
printf("Encrypted string\n");
for(i=0;i<length_of_pt;i++)
{
printf("%c",ct[i]);
}
printf("\n");
printf("Decrypted string\n");
for(i=0;i<length_of_pt;i+=2)
{
av1=(int)ct[i]-97;
av2=(int)ct[i+1]-97;
row1=flag[av1]/10;
col1=flag[av1]%10;
row2=flag[av2]/10;
col2=flag[av2]%10;
if(row1==row2)
{
if(col1-1==-1)
col1=5;
if(col2-1==-1)
col2=5;
ct[i]=(char)play[row1][(col1-1)%5];
ct[i+1]=(char)play[row1][(col2-1)%5];
}
else if(col1==col2)
{
if(row1-1==-1)
row1=5;
if(row2-1==-1)
row2=5;
ct[i]=(char)play[(row1-1)%5][col1];
ct[i+1]=(char)play[(row2-1)%5][col1];
}
else
{
ct[i]=(char)play[row1][col2];
ct[i+1]=(char)play[row2][col1];
}
}
ct[length_of_pt]='\0';
for(i=0;i<length_of_pt;i++)
{
printf("%c",ct[i]);
}
}
Output :