### WAP to Implement Play fair Algorithm

#include <stdio.h>
#include<conio.h>
#define siz 5
char ci[25];
int r=0;

void encrypt(int *i, int *j)  //Encryption code
{
(*i)++,(*j)++;
if((*i)==siz) *i=0;
else if((*j)==siz) *j=0;
}
void playfair(char ch1,char ch2, char mat[siz][siz])
{
int j,m,n,p,q,c,k;
for(j=0,c=0;(c<2)||(j<siz);j++)
for(k=0;k<siz;k++)
if(mat[j][k] == ch1) //Calculating thr position of first character
m=j,n=k,c++;
else if(mat[j][k] == ch2) //Calculating thr position of second character
p=j,q=k,c++;
if(m==p)
encrypt(&n,&q);  //In the same row
else if(n==q)
encrypt(&m,&p);  //In the same column
else
n+=q,q=n-q,n-=q; //In different column and row
printf("%c%c",mat[m][n],mat[p][q]);
ci[r++]=mat[m][n];
ci[r++]=mat[p][q];
}

void decrypt(int *i, int *j)  //Decryption code
{
(*i)--,(*j)--;
if((*i)==siz) *i=0;
else if((*j)==siz) *j=0;

}
void playfair1(char ch1,char ch2, char mat[siz][siz])
{
int j,m,n,p,q,c,k;
for(j=0,c=0;(c<2)||(j<siz);j++)
for(k=0;k<siz;k++)
if(mat[j][k] == ch1)
m=j,n=k,c++;
else if(mat[j][k] == ch2)
p=j,q=k,c++;
if(m==p)                  //Same row
decrypt(&q,&n);
else if(n==q)        //Same Column
decrypt(&p,&m);
else
n+=q,q=n-q,n-=q;
printf("%c%c",mat[m][n],mat[p][q]);
}
void main()
{
char mat[siz][siz],key[10],str[25]={0};
int m,n,i,j;
char temp;
clrscr();
printf("Demonstration of Playfair method\n\n");
printf("\nEnter Key String:");
gets(key);
m=n=0;
//Storing the key values in the matrix
for(i=0;key[i]!='\0';i++)
{
for(j=0;j<i;j++)
if(key[j] == key[i]) break;
if(key[i]=='j') key[i]='i';
if(j>=i)
{
mat[m][n++] = key[i];
if(n==siz)
n=0,m++;
}
}
//Storing the rest alphabet in the matrix
for(i=97;i<=122;i++)
{
for(j=0;key[j]!='\0';j++)
if(key[j] == i)
break;
else if(i=='j')
break;
if(key[j]=='\0')
{
mat[m][n++] = i;
if(n==siz) n=0,m++;
}
}
printf("\nEnter input String to encrypt:");
gets(str);
printf("\n\nMatrix :\n");
for(i=0;i<siz;i++)
{
for(j=0;j<siz;j++)
printf("%c\t",mat[i][j]);
printf("\n");
}
printf("\n\nEntered text :%s \n\nCipher Text :",str);
for(i=0;str[i]!='\0';i++)
{
temp = str[i++];
if(temp == 'j') temp='i';
if(str[i]=='\0')
playfair(temp,'x',mat);
else
{
if(str[i]=='j') str[i]='i';
if(temp == str[i])
{
playfair(temp,'x',mat);
i--;
}
else
playfair(temp,str[i],mat);
}
}
ci[r]= '\0';
for(i=0;ci[i]!='\0';i++)
str[i]=ci[i];
str[i]='\0';
printf("\n\nThe Decrypted Text:");
for(i=0;str[i]!='\0';i++)
{
temp = str[i++];
if(temp == 'j') temp='i';
if(str[i]=='\0')
playfair1(temp,'x',mat);
else
{
if(str[i]=='j') str[i]='i';
if(temp == str[i])
{
playfair1(temp,'x',mat);
i--;
}
else
playfair1(temp,str[i],mat);
}
}
getch();
}