Hello friends, I am very happy to write my first post about
implementation of Playfair cipher algorithm in c.
For any query regarding c/c++ feel free to contact me on khimanichirag@gmail.com. I try my best to solve it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<graphics.h>
void line(int a)
{
int i;
printf("\n");
for(i=0;i<a;i++)
{
printf("*");
}
printf("\n");
}
char s[30];
void main()
{
char c[27],k[30],temp[40],matrix[5][5],first,second;
int i,index,j,t,t1,p,p1,gd,gm;
initgraph(&gm,&gd, "c:\\tc\\bgi");
clrscr();
cleardevice();
//-------------------------ABCD in c[]---------------------------------
setcolor(2);
outtextxy(400,460,"Prepared By:Khimani Chirag");
setcolor(2);
outtextxy(150,10,"Welcome To Playfair Cipher Encryption");
for(i=97;i<=122;i++)
{
c[i-97]=i;
}
//---------------------------------------------------------------------
printf("\n\n");
line(50);
printf("enter the plain text: ");
gets(s);
printf("\nenter key for playfair cipher: ");
gets(k);
line(50);
//---------------------------put c[]<--* when key-----------------------
for(i=0;k[i]!='\0';i++)
{
index=k[i]-97;
if(c[index]=='*')
{
k[i]='*';
}
else
{
c[index]='*';
}
}
//------------------------------put key[] in variable-------------------
i=0;
j=0;
while(k[i] !='\0')
{
if(k[i]!='*' )
{
temp[j]=k[i];
j++;
}
i++;
}
//-----------------------------put c[] in temp variable------------------
i=0;
while(c[i] !='\0')
{
if(c[i]!='*' && c[i]!='j' )
{
temp[j]=c[i];
j++;
}
i++;
}
printf("\nyour matrix is:\n");
line(20);
//-----------------------------matrix printing---------------------------
t=0;
for(i=0;i<5;i++)
{
printf("* ");
for(j=0;j<5;j++)
{
printf("%c ",temp[t]);
matrix[i][j]=temp[t];
t++;
}
printf(" *");
if(i!=4)
printf("\n");
}
line(20);
printf("\nyour cipher text is: ");
//------------------------------------------------------------------------
i=0;
if(strlen(s)%2!=0)
{
while(s[i]!='\0')
{
i++;
}
s[i]='x';
s[i+1]='\0';
}
for(index=0;index<strlen(s);index+=2)
{
first=s[index];
second=s[index+1];
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(matrix[i][j]==first)
{
t=i;
t1=j;
}
if(matrix[i][j]==second)
{
p=i;
p1=j;
}
}
}
if(p==t)
{
if(p1==4)
{
p1=-1;
}
if(t1==4)
{
t1=-1;
}
printf("%c%c",matrix[t][t1+1],matrix[p][p1+1]);
}
else if(p1==t1)
{
if(p==4)
{
p=-1;
}
if(t==4)
{
t=-1;
}
printf("%c%c",matrix[t+1][t1],matrix[p+1][p1]);
}
else
{
printf("%c%c",matrix[t][p1],matrix[p][t1 ]);
}
}
getch();
}