Hello there!
Well i'll present my problem: As a part of a bigger program I was trying to encrypt a file using basic xor encrypting, I can encrypt and decrypt files easily. The problem is in my "bigger" program I would like to open the file and read its data but what if its encrypted? well I went over this thinking about using a magic key at the start of the encrypted file for example "EN\n" then if I read the first line and the program found the magic key it would know that the file is encrypted, decrypt it and read the data. Problem comes when trying to decrypt and depending on the key even trying to encrypt since sometimes I experienced that \n wasn't being printed to the file... Here's a sortened version of a small encrypt program I made to test the problem...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 256
#define MAGICKEY "EN"
void encrypt_file(FILE *src, FILE *dest, char *key);
void copy_file(FILE *src, FILE *dest);
int main()
{
FILE *f, *tmp, *tmp2;
char s[MAXLEN], key[MAXLEN], magic[MAXLEN];
printf("Enter file name: ");
fflush(stdin);
gets(s);
f = fopen(s, "r");
if(f == NULL){
printf("ERROR: Couldn't open file %s\n", s);
return -1;
}
tmp = fopen("tmp.txt", "w");
if(tmp == NULL){
printf("ERROR: Couldn't write temp file\n");
return -1;
}
printf("Enter key: ");
fflush(stdin);
gets(key);
fscanf(f, "%s", magic);
if(strcmp(magic, MAGICKEY) == 0){
fgetc(f); // get rid of '\n'
copy_file(f, tmp);
tmp2 = fopen("tmp2.txt", "w");
if(tmp2 == NULL){
printf("ERROR: Couldn't write temp file\n");
return -1;
}
encrypt_file(tmp, tmp2, key);
fclose(tmp2);*/
fclose(tmp);
fclose(f);
remove(s);
remove("tmp.txt");
rename("tmp2.txt", s);
}else{
rewind(f);
encrypt_file(f, tmp, key);
rewind(tmp);
fprintf(tmp, "%s\n", MAGICKEY);
fclose(tmp);
fclose(f);
remove(s);
rename("tmp.txt", s);
}
return 0;
}
void encrypt_file(FILE *src, FILE *dest, char *key){
int i, b;
i = 0;
while((b = fgetc(src)) != EOF){
fputc(b ^ key[i], dest);
++i;
if(i == strlen(key))
i = 0;
}
}
void copy_file(FILE *src, FILE *dest){
int c;
while((c = fgetc(src)) != EOF)
putc(c, dest);
}
I tried binary reading mode but doesn't seem to work cause I have to remove the \n and since this varies from OS to OS as I understood, I'm having a headache and don't know how to go about it...
Thanks in advance!