I am trying to write an simple program to encrypt/decrypt the contents of a text file.
This is the function that I am using:
/*
* Encrypt/Decrypt a file by conducting an XOR operation on the contents
* of the file and the key provide.
* Returns 0 if successful and -1 if fail
*
* char *filename: The file to be encrypted/decrypted
* char *key: The key to encrypt/decrypt the file with
*/
int encrypt (char *filename, char *key)
{
FILE *fptR; /* File pointer to read from the file to be encrypted/decrypted */
FILE *fptW; /* File pointer to write to the file to be encryted/decrypted */
char reader; /* To store each char read from the file */
int keysize; /* Size of the key used to encrypt/decrypt */
int i; /* A counter to iterate the key */
char out[MAX_STRING]; /* Name of the output file */
/* Open the file for reading/writing */
if( ( fptR = fopen(filename, "r+") ) == NULL) {
printf("ERROR: file reader cannot be open\n");
return -1;
}
if( ( fptW = fopen(filename, "r+") ) == NULL) {
printf("ERROR: file writer cannot be open\n");
return -1;
}
/* Start Encrypting/decrypting file */
i = 0;
keysize = strlen(key);
reader = fgetc(fptR);
while(reader != EOF) {
/* Encrypt with key */
reader = reader ^ key[i];
/* Write Encrypted data back to file */
fputc(reader, fptW);
/* Update key & file pointers */
i = (i+1)%keysize;
reader = (char)fgetc(fptR);
}
/* Close files */
fclose(fptW);
fclose(fptR);
return 0;
}
It seems to works with a simple "hello world" text file. But when I try to decrypt a C source file, only the first few characters and the last few characters got decypted. The rest inbetween is still rubbish
Could it be fgetc?
Thanks in advance



LinkBack URL
About LinkBacks




