Mar 18, 2010

Polyalphabatic cipher encryption and decryption

//POLYALPHABATIC CIPHER ENCRYPTION
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int start=98,i,temp=97,j,k,m,n,l;
char plain[100],key[100],cipher[100],arr[27][27],ch1,ch2;
FILE *f1,*f2;
clrscr();
//code for matrix generation
for(i=0;i<27;i++)
{
for(j=0;j<27;j++)
{
if(temp>122 )
temp=32;
arr[i][j]=temp++;
if(temp==33)
temp=97;
}
temp=start++;
}
//printing matrix
for(i=0;i<27;i++)
{
for(j=0;j<27;j++)
printf("%c",arr[i][j]);
printf("\n");
}
i=0;
f1=fopen("plain.txt","r");
while((l=getc(f1))!=EOF)
plain[i++]=l;
plain[i]=NULL;
fclose(f1);
i=0;
f1=fopen("key.txt","r");
while((l=getc(f1))!=EOF)
key[i++]=l;
key[i]=NULL;
fclose(f1);
temp=0;
printf("\nplain text: %s\n",plain);
for(i=strlen(key);i<strlen(plain);i++)
{
if(temp>strlen(key))
temp=0;
key[i]=key[temp++];
}
key[i]=NULL;
printf("key:        %s\n",key);
for(i=0;i<strlen(plain);i++)
{
if(plain[i]!=32)
m=plain[i]-97;
else
m=26;
n=key[i]-97;
cipher[i]=arr[m][n];
}
cipher[i]=NULL;
f1=fopen("cipher.txt","w");
for(i=0;i<strlen(cipher);i++)
putc(cipher[i],f1);
fclose(f1);
printf("cipher text:%s",cipher);
getch();


}

//POLYALPHABATIC CIPHER DECRYPTION
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int start=98,i,temp=97,j,k,m,n,l;
char plain[100],key[100],cipher[100],arr[27][27],ch1,ch2;
FILE *f1,*f2;
clrscr();
//code for matrix generation
for(i=0;i<27;i++)
{
for(j=0;j<27;j++)
{
if(temp>122 )
temp=32;
arr[i][j]=temp++;
if(temp==33)
temp=97;
}
temp=start++;
}
//printing matrix
for(i=0;i<27;i++)
{
for(j=0;j<27;j++)
printf("%c",arr[i][j]);
printf("\n");
}
i=0;
f1=fopen("cipher.txt","r");
while((l=getc(f1))!=EOF)
cipher[i++]=l;
cipher[i]=NULL;
fclose(f1);
i=0;
f1=fopen("key.txt","r");
while((l=getc(f1))!=EOF)
key[i++]=l;
key[i]=NULL;
fclose(f1);
temp=0;
printf("\ncipher text:%s\n",cipher);
for(i=strlen(key);i<strlen(cipher);i++)
{
if(temp>strlen(key))
temp=0;
key[i]=key[temp++];
}
key[i]=NULL;
k=0;
printf("key:        %s\n",key);
for(i=0;i<strlen(cipher);i++)
{
for(j=0;j<27;j++)
{
if(cipher[k]==arr[key[i]-97][j])
break;
}
plain[k++]=arr[0][j];
}
plain[k]=NULL;
f1=fopen("plain.txt","w");
for(i=0;i<strlen(plain);i++)
putc(plain[i],f1);
fclose(f1);
printf("plain text: %s\n",plain);
getch();
}

No comments:

Post a Comment