Hi

I've attempted to create a little app which encrypts and decrypts a file using the XOR cipher. However, it only encrypts/decrypts the first few lines and I'm not sure where I'm going wrong. Advice appreciated.

Ricky

My code:

//XOR Encryption

#include <stdio.h>
#include <string.h>

//XOR Encryption key
char XORkey [] = "simples";


void XOR_encrypt(char* input_file, char* output_file, char* key)
{
	//Open input and output files
	FILE* input = fopen(input_file, "r");
	FILE* output = fopen(output_file, "w");

	//Check input file
	if (input == NULL)
	{
		printf("Input file cannot be read.\n");
		return;
	}
		
	//Check output file
	if (output == NULL)
	{
		printf("Output file cannot be written to.\n");
		return;
	}
	
	int key_count = 0; //Used to restart key if strlen(key) < strlen(encrypt)
	int encrypt_byte;

	while( (encrypt_byte = fgetc(input)) != EOF) //Loop through each byte of file until EOF
	{
		//XOR the data and write it to a file
		fputc(encrypt_byte ^ key[key_count], output);

		//Increment key_count and start over if necessary
		key_count++;
		if(key_count == strlen(key))
		{
			//printf("%i", key_count);
			key_count = 0;
		}
	}

	//Close files
	fclose (input);
	fclose (output);

}

void main()
{
	char input[] = "C:\\test.txt";
	char output[] = "C:\\test_encrypted.txt";

	//XOR data and write it to file
	XOR_encrypt(input, output, XORkey);

	getchar();
}

Recommended Answers

All 2 Replies

First of all, 'main' returns 'int'. Always.

Secondly, when encrypting a file, you should open both the input and the output as binary files. FILE* input = fopen(input_file, "rb"); Reading them as ASCII files is problematic, since the program is translating Windows newlines to special characters, which shouldn't really be encrypted.

Other than that, it's working just fine for me.

Thanks, changing the fopen modes to binary, "rb" and "wb", worked. I forgot about carriage-returns and linefeed characters.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.