I'm trying to encrypt/decrypt a file using XOR. I have the following encryption/decryption routine where every byte is xor'd and the result is being subtracted by the value of the byte that is located at the previous location. The ASM representation is as follows
crypt:
mov dl, [eax+ecx] ; read byte
xor dl, 0C5h ; xor it with oxC5
sub dl, [eax+ecx-1] ; sub the previous byte
mov [eax+ecx], dl ; save the new byte
dec eax ; decrement pointer
test eax, eax
jg short crypt ;
That is what my encryption routine should look like, I'm trying to port this this C/C++. My code is as follows
#include <stdio.h>
unsigned int xorkey = 0xC5;
int main(int argc, char *argv[])
{
if(argc < 3)
{
printf("usage: encoder input output\n");
return -1;
}
FILE *in = fopen(argv[1], "rb");
if(in == NULL)
{
printf("failed to open: %s", argv[2]);
return -1;
}
FILE *out = fopen(argv[2], "wb");
if(out == NULL)
{
fclose(in);
printf("failed to open '%s' for writing.",argv[2]);
return -1;
}
int count;
char buffer[1024];
while(count = fread(buffer, 1, 1024, in))
{
int i;
int end = count;
for(i = 0;i < end; ++i)
{
((unsigned int *)buffer)[i] ^= xorkey;
}
if(fwrite(buffer, 1, count, out) != count)
{
fclose(in);
fclose(out);
printf("fwrite() error\n");
return -1;
}
}
fclose(in);
fclose(out);
return 0;
}
I cannot figure out how to do the subtracting of bytes in C++. The XOR routine itself looks correct though, no? Please note that I'm also trying to encrypt the file starting from the end of the file till the beginning. Any ideas?
Thanks!