Fully working code:
Code:
#include <iostream>
using namespace std;
void XOREncrypt(char *pfile, char *pkey); // Forward declaration
int main()
{
char tmpfile[50]; // stores our filename
char key[50]; // stores our encryption key
while(1) // Repeat for eternity :)
{
cout<<"Enter the file name: "; // No need to explain
cin>>tmpfile; // ^
cout<<"Encryption key: "; // ^
cin>>key; // ^
XOREncrypt(tmpfile, key); // Call the XOREncrypt function
}
return 0;
}
void XOREncrypt(char *pfile, char *pkey)
{
FILE *input, *output; // File pointers <3
input=fopen(pfile, "rb"); // open the input file(mode: read+binary)
output=fopen("output.txt", "wb"); // open the output file(mode: write+bin)
if(input != NULL && output != NULL) // if they both opened succesfully
{
unsigned char buffer[64]; // unsigned char buffer to unfuck our previous errors
// Any size will do, it tries to read 64 bytes a time now
size_t i, j, rdln; // size_t because thats what fread returns
i=0;j=0;rdln=0; // init to 0
do // do
{
rdln = fread(buffer, sizeof(*buffer),sizeof(buffer),input); // read 64 bytes from input
for(i=0;i<rdln;++i)// 0 to the amount of chars we succesfully read from the input file
{
buffer[i] ^= pkey[j++]; // XOR with the key
if(j==strlen(pkey)) // if j is the strlen of the key
{
j=0; // reset it to 0
}
}
fwrite(buffer, sizeof(*buffer), rdln, output); // XOR'd buffer -> output file
} while(rdln==sizeof(buffer)); // while characters read == size of the buffer(64)
}
fclose(input); // close the input file
fclose(output); // close the output file
}
using unsigned char fixed the issues.
signed char can contain values between -128 to +127
unsigned char can contain values between 0 and 256 which is what we want.