So I’m trying to making a file encrypting program in C (by the way I’m kind of new to C) so I wrote this simple XOR file encryption code:
#include <stdio.h>
#include <string.h>
int main()
{
char fileName1[35] = {'\0'}; //Name of original file
char fileName2[35] = {'\0'}; //Name of encrypted file
char keyString[20] = {'\0'}; //Key determines result encryption
FILE* originalFile; //File to be encrypted
FILE* cryptedFile; //The encrypted file
int c; //byte read from original file
printf("Enter file location followed by name of the file you want to encrypt: ");
scanf("%s", fileName1);
printf("Enter file location followed by name of the encrypted file: ");
scanf("%s", fileName2);
printf("Enter your key (Encryption changes based on Key): ");
scanf("%s", keyString);
originalFile = fopen(fileName1, "rb"); //rb to read file bytes
cryptedFile = fopen(fileName2, "wb"); //wb to write bytes to file
if(originalFile != NULL && cryptedFile != NULL){
while( (c = getc(originalFile)) != EOF ){
int x;
for(x=0; x<strlen(keyString); x++){
c ^= keyString[x];
putc(c, cryptedFile);
}
}
fclose(originalFile);
fclose(cryptedFile);
}
return 0;
}
So to test this program I created a file called file1.txt and run the encryption program giving it the second file as file2.txt and key as secret. Then I ran the program again but this time on the encrypted file2.txt and created a file3.txt with the same key secret. Since it was the same key the file3.txt should be the same as file1.txt but file3.txt has random contents in it. So what am I doing wrong?
Your program outputs too much data; try checking the sizes of file1.txt, file2.txt and file3.txt. The problem in is this section:
There’s two nested loops, so the whole inner loop is executed for each input character. Try a new
c = getc()inside the inner loop and break out of both loops if EOF is reached, or flatten the loops into one, using ac ^= keyString[(x++) % strlen(keyString)];.