Mar 18, 2010

Caesar cipher encryption and decryption

//CAESAR CIPHER ENCRYPTION
//copyright jayeshaminnew@gmail.com
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
//declaring variables
FILE *f1,*f2;
int i,j=0,k,l,key,temp,temp1,flag=0;
char plain[50],cipher[50],m;
clrscr();
//reading plain text
f1=fopen("plain.txt","r");
while((l=getc(f1))!=EOF)
plain[j++]=l;
plain[j]=NULL;
fclose(f1);
printf("your plain text is:%s\n",plain);
scanf("%d",&key,printf("enter key:"));
for(i=0;i<j;i++)
{
temp=plain[i];
temp1=temp;
temp1+=key;
if(temp1>122 && islower(temp))
temp1-=26;
else if(temp1>90 && isupper(temp))
temp1-=26;
else if(!((temp>=97 && temp<=122) || (temp>=65 && temp<=90)))
{
flag=1;
}
if(flag==0)
cipher[i]=temp1;
else
cipher[i]=temp;
flag=0;
}
cipher[i]=NULL;
//writing cipher text into file
f2=fopen("cipher.txt","w");
for(i=0;i<strlen(cipher);i++)
putc(cipher[i],f2);
fclose(f2);
printf("your cipher text is:%s",cipher);
getch();
}

//CAESAR CIPHER DECRYPTION

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<process.h>
void main()
{
FILE *f1,*f2;
int i,j=0,k,l,key,temp,temp1,flag=0;
char plain[50],cipher[50],meaning;
clrscr();
f1=fopen("cipher.txt","r");
while((l=getc(f1))!=EOF)
cipher[j++]=l;
cipher[j]=NULL;
fclose(f1);
j=0;
for(i=0;i<26;i++)
{
for(j=0;j<strlen(cipher);j++)
{
temp=cipher[j];
temp1=temp;
temp1-=i;
if(temp1<97 && islower(temp))
temp1+=26;
else if(temp1<65 && isupper(temp))
temp1+=26;
else if(!((temp>=97 && temp<=122) || (temp>=65 && temp<=90)))
{
flag=1;
}
else
{}
if(flag==0)
plain[j]=temp1;
else
plain[j]=temp;
flag=0;
}
plain[j]=NULL;
printf("Message:%s",plain);
printf("\nis it meaning ful msg?? Y/N?\n");
scanf("%s",&meaning);
if(meaning=='y' || meaning=='Y')
{
printf("your plain text is: %s",plain);
getch();
exit(0);
}
}
getch();
}

No comments:

Post a Comment