Hi all, I'm just getting back in to C programming after some time and I thought I would start off with a simple XOR encryption program. However I'm having trouble getting it to work. The code in prompt() function works great when it is just placed in side of main() however I want to be able to pass my arrays and file pointers to the prompt function to make the code more modular. Any help is much appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char encrypt(char, char *);
int prompt(FILE **, FILE **, char *, char *, char *, char *);
int main()
{
FILE *inputFile, *outputFile; // Self explantory
char fileIn[256] = {'\0'}, fileOut[256] = {'\0'},
password[30] = {'\0'}, password2[30] = {'\0'}; /* Input file name, output file name and password and password2 */
int holding = 1, fcharin = 1, retStat; /* Where we keep the byte from the file thats been
encrypted and the byte read from the file */
printf("XORencrypt by David James\nCreated: 29/05/08\n\n");
retStat = prompt(&inputFile, &outputFile, fileIn, fileOut, password, password2);
/* Below is the encryption part. Each byte from the file is read in to a (char) then XOR'd with element 0
of the password array, then element 1 then element 2 etc until NULL is reached in the password array. Then
the now encrypted (char) byte is written to the output file.
*/
while ( (fcharin = fgetc(inputFile)) != EOF ) {
holding = encrypt(fcharin, password);
fputc(holding, outputFile);
}
printf("\nEncryption/Decryption complete!\n");
return 0;
}
/* The XOR encryption function */
char encrypt(char fcharin, char *password)
{
int i = 0, holding = 0;
for ( i = 0; password != '\n'; i++ ) {
holding = fcharin ^ password;
}
return holding;
}
/* If the user gives no command line arguments */
int prompt(FILE **inputFile, FILE **outputFile, char *fileIn, char *fileOut, char *password, char *password2)
{
printf("File to encrypt/decrypt?: ");
scanf("%255s", fileIn);
if ( (*inputFile = fopen(fileIn, "rb")) == NULL ) {
printf("Error opening file.\n");
exit(1);
}
printf("Save the encrypted/decrypted file as?: ");
scanf("%255s", fileOut);
do {
printf("Enter a password (less than 30 characters [no spaces]): ");
scanf("%29s", password);
printf("Again: ");
scanf("%29s", password2);
} while ( strcmp(password, password2) );
if ( (*outputFile = fopen(fileOut, "wb")) == NULL ) {
printf("Error writing file %s or it could not be opened.\n", fileOut);
exit(1);
}
return 0;
}