Hey guys,
I'm a long time lurker, and first time poster. Please be kind. Anyways, for one of my classes, Principles of Algorithm Design 1, we had an assignment where we had to create a program that would encrypt and then de-encrypt a message by offsetting the characters by a user specified amount as well as inserting random characters. As much as I tried, I found that ultimately... I screwed it up big time. I turned the assignment in for partial credit, but it is still bugging me, so I've decided to come to you kind folk for help. Heres my code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
char encrypt(int offset, int random){
char cur;
int pos=1;
FILE* fin=fopen("Input.bak", "r");
FILE* fout=fopen("Output.bak", "w");
printf("Please ensure that the message you want to encrypt \n is in file Input.bak\n ");
while ((fscanf(fin,"%c", &cur))==1) {
if ((pos%random)==0)
fprintf(fout,"%c%c ", (rand()%26+'a'), (cur+offset));
else
fprintf(fout,"%c", (cur+offset));
pos++;}
fclose(fout);
fclose(fin);
return cur;
}
char decrypt(int offset, int random){
char cur;
int pos=1;
FILE* fin=fopen("Output.bak", "r");
FILE* fout=fopen("Unencrypted.bak", "w");
printf("Please ensure that the message you want to decrypt \n is in file Output.bak\n ");
while ((fscanf(fin,"%c", &cur))==1) {
if ((pos%(random+5))==0)
fscanf(fout,"%*c");
else fprintf(fout,"%c", (cur-offset));
pos++;
}
fclose(fout);
fclose(fin);
return cur;
}
int main(void){
char c;
int offset;
int random;
printf("The purpose of this program is to encrypt and decrypt message.\n");
printf("Please enter e to encrypt or d to decrypt.\n");
scanf("%c", &c);
if ((c == 'e')) printf("You chose to encrypt.\n");
else if ((c == 'E')) printf("You chose to encrypt.\n");
else if ((c == 'd')) printf("You chose to decrypt.\n");
else if ((c == 'D')) printf("You chose to decrypt\n");
else {printf("You didn't enter either e or d. Please follow the instructions next time.\n");
scanf(" *c");
return 101;
}
printf("Please enter the offset.\n");
scanf("%d", &offset);
printf("Please enter the number of spaces between random characters.\n");
scanf("%d", &random);
printf("Your user-defined offset is %d and the number of spaces between random characters is %d.", offset, random);
if ((c == 'e')) encrypt(offset, random);
else if ((c == 'E')) encrypt(offset, random);
else if ((c == 'd')) decrypt(offset, random);
else if ((c == 'D')) decrypt(offset, random);
else printf("Since you didn't choose either e or d, its just a bit worthless.\n");
return 0;
}
Any help in solving this problem would be greatly appreciated. Personally, I think that the decryption isnt removing the random characters correctly as the message comes out somewhat recognizable in some cases.
Thanks again!