Tuesday, February 17, 2015

Caesar cipher encryption-decryption

#include<stdio.h>
#include<conio.h>
void main()
{
char pt[100],ct[100],dt[100];
int i,key;
clrscr();
printf("ENter the plain text and press ']' to terminate\n");
for(i=0; i<100; i++)
{
            scanf("%c",&pt[i]);
            if(pt[i]==']')
            {
                        pt[i]='\0';
                        break;
            }
}
printf("ENter the key\n");
scanf("%d",&key);
for(i=0; pt[i]!='\0'; i++)
{
            if(pt[i]>64 && pt[i]<91)
                        ct[i]=(pt[i]-65+key)%26+65;

            if(pt[i]>96 && pt[i]<123)
                        ct[i]=(pt[i]-97+key)%26+97;

            if(pt[i]==32)
                        ct[i]=pt[i];
}
printf("Plain text :\n");
for(i=0; pt[i]!='\0'; i++)
printf("%c",pt[i]);
printf("\nCeasar cipher:\n");
for(i=0; ct[i]!='\0'; i++)
printf("%c",ct[i]);
printf("\n");
for(key=0; key<26; key++)
{
            printf("For key %d ",key);
            for(i=0; ct[i]!='\0'; i++)
            {
                        if(ct[i]>64 && ct[i]<91)
                        {
                                    dt[i]=(ct[i]-39-key)%26+65;
                                    printf("%c",dt[i]);
                        }
                        if(ct[i]>96 && ct[i]<123)
                        {
                                    dt[i]=(ct[i]-71-key)%26+97;
                                    printf("%c",dt[i]);
                        }
                        if(ct[i]==32)
                        {
                                    dt[i]=ct[i];
                                    printf("%c",dt[i]);
                        }
            }
                        printf("\n");
}
getch();
}

No comments:

Post a Comment