Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 4

#include <stdio.

h>
#include <string.h>
#define MAX 1000
void railencrypt(int railkey, char*inbuf, char*outbuf)
{
int i,j=0,p;

for(p=0;p<railkey;p++) {
for(i=0;i<strlen(inbuf);i++) {
if(i%(2*(railkey-1)) == p || i%(2*(railkey-1))==2*(railkey-1)-p)
outbuf[j++] = inbuf[i];
}
}
outbuf[j] = '\0';
}
void raildecrypt(int railkey, char*inbuf, char*outbuf)
{
int i,j=0,p;

for(p=0;p<railkey;p++) {
for(i=0;i<strlen(inbuf);i++) {
if(i%(2*(railkey-1)) == p || i%(2*(railkey-1))==2*(railkey-1)-p)
outbuf[i] = inbuf[j++];
}
}
outbuf[j] = '\0';

}
void main()
{
FILE *fpi,*fpo;
int railkey,option;
char inbuf[MAX], outbuf[MAX];

do {
printf("RAIL CIPHER PROGRAM: \n");
printf("1. Encryption\n2. Decryption\n3.Exit\n");
scanf("%d",&option);
printf("Enter the Rail KEY : ");
scanf("%d",&railkey);
if(option == 1) {
fpi = fopen("encryt.txt","r");
if(fpi == NULL) {
printf("Error opening encrypt.txt file\n");
break;
}
fpo = fopen("decrypt.txt","w");
if(fpo == NULL) {
printf("Error opening decrypt.txt file\n");
break;
}
while(1) {
fgets(inbuf,MAX,fpi);

if(feof(fpi)) break;
// Removing the CR from the line
if(inbuf[strlen(inbuf)-1] == 0x0A) inbuf[strlen(inbuf)-1] = '\0';
railencrypt(railkey, inbuf,outbuf);
// Adding the CR to the output buffer
outbuf[strlen(outbuf)] = 0x0A;
fputs(outbuf,fpo);
}
fclose(fpi);
fclose(fpo);
} else (option == 2) {
fpi = fopen("decryt.txt","r");
if(fpi == NULL) {
printf("Error opening decrypt.txt file\n");
break;
}
fpo = fopen("output.txt","w");
if(fpo == NULL) {
printf("Error opening output.txt file\n");
break;
}
while(1) {
fgets(inbuf,MAX,fpi);
if(feof(fpi)) break;
// Removing the CR from the line
if(inbuf[strlen(inbuf)-1] == 0x0A) inbuf[strlen(inbuf)-1] = '\0';

raildecrypt(railkey, inbuf,outbuf);
// Adding the CR to the output buffer
outbuf[strlen(outbuf)] = 0x0A;
fputs(outbuf,fpo);
}
fclose(fpi);
fclose(fpo);
}
} while(option != 3);
}

You might also like