Mono-alphabetic Cipher Implementation - C Tutorial
A mono-alphabetic cipher is a type of simple substitution cipher. In this cipher technique each letter of the plaintext is replaced by another letter in the cipher-text. An example of a mono-alphabetic cipher key follows:
Plain Text >>> a b c d e f g h i j k l m n o p q r s t u v w x y z
Cipher Text >>> z w x y o p r q a h c b e s u t v f g j l k m n d i
This key means that any ‘a’ in the plaintext will be replaced by a ‘z’ in the cipher-text, any ‘z’ in the plaintext will be replaced by a ‘i’ in the cipher-text, and so on.
The following program shows the simple implementation of mono-alphabetic cipher technique in c language for encrypting and decrypting file
[crayon ]
#include <stdio.h>
#include <string.h>
#define FILE_NAME_MAX 30
extern char alpha[26][2]={ {‘a’,’z’},{‘b’,’w’},{‘c’,’x’},{‘d’,’y’},{‘e’,’o’} ,{‘f’,’p’},{‘g’,’r’},{‘h’,’q’},{‘i’,’a’},{‘j’,’h’}, {‘k’,’c’},{‘l’,’b’},{‘m’,’e’},{‘n’,’s’},{‘o’,’u’},{‘p’,’t’},{‘q’,’v’},{‘r’,’f’},{‘s’,’g’},{‘t’,’j’}, {‘u’,’l’},{‘v’,’k’},{‘w’,’m’},{‘x’,’n’},{‘y’,’d’}, {‘z’,’i’} };
int encrypt();
int decrypt();
int main()
{
int choice;
while (1)
{
printf(“\nEnter Your Choice : \n”);
printf(“\n1. Encrypt File\n”);
printf(“\n2. Decrypt File\n”);
printf(“\n3. Exit\n\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: encrypt();
break;
case 2: decrypt();
break;
case 3:
exit(0);
default:
printf(“\nPlease Enter valid choice\n”);
break;
}
}
}
int decrypt()
{
char filename[FILE_NAME_MAX];
int i=0;int s;
FILE *fp;
printf(“\nEnter file name\n\n”);
scanf(“%s”,filename);
if( fp = fopen(filename,”r+”))
{printf(“\nFile opened Successfully\n\nDecrypted As :>>>>>> \n\n”);}
else
{printf(“\nFailed to Open File\n\n”); return 0;}
while((s=getc(fp))!=EOF)
{ for(i=0;i<=25;i++)
{ if(s==32){printf(” “);break;}
if(alpha[i][1]==(char)s)
{
fseek(fp, -1,SEEK_CUR);
printf(“%c”,alpha[i][0]);
putc(alpha[i][0],fp);
break;
}
if(toupper(alpha[i][1])==(char)s)
{
fseek(fp, -1,SEEK_CUR);
printf(“%c”,toupper(alpha[i][0]));
putc(toupper(alpha[i][0]),fp);
break;
}
}
}
printf(“\n\n”);
fclose(fp);
}
int encrypt()
{
char filename[FILE_NAME_MAX];
int i=0;int s;
FILE *fp;
printf(“\nEnter file name\n\n”);
scanf(“%s”,filename);
if( fp = fopen(filename,”r+”))
{printf(“\nFile opened Successfully\n\nEncrypted As :>>>>>> \n\n”);}
else
{printf(“\nFailed to Open File\n\n”); return 0;}
while((s=getc(fp))!=EOF)
{ for(i=0;i<=25;i++)
{ if(s==32){printf(” “);break;}
if(alpha[i][0]==(char)s)
{
fseek(fp, -1,SEEK_CUR);
printf(“%c”,alpha[i][1]);
putc(alpha[i][1],fp);
break;
}
if(toupper(alpha[i][0])==(char)s)
{
fseek(fp, -1,SEEK_CUR);
printf(“%c”,toupper(alpha[i][1]));
putc(toupper(alpha[i][1]),fp);
break;
}
}
}
printf(“\n\n”);
fclose(fp);
}
[/crayon]
Comments
Post a Comment