Simple XOR encryption routine in C/C++

穿精又带淫゛_ 提交于 2019-11-29 17:40:58

Here's how you could write that assembly language function in C. I've kept the variable names the same as the register names so you can see how the various parts match up.

void do_xor_crypt(char *buffer, int count) {
    char *ecx = buffer;
    int eax = count - 1;
    if (eax > 0) {
        do {
            char dl = ecx[eax];
            dl ^= 0xC5;
            dl -= ecx[eax-1];
            ecx[eax] = dl;
            eax--;
        } while (eax > 0);
    }
}

Note that I have checked to make sure eax is greater than zero (meaning count is two or more) so that the loop has something to subtract. You could integrate this code into your reading loop like:

while (count = fread(buffer, 1, 1024, in))
{
    do_xor_crypt(buffer, count);
    if (fwrite(buffer, 1, count, out) != count)
    {
        // ...
    }
}

There are a couple things wrong with your C code.

The asm code starts at the end of the buffer and works its way down and stops when eax == 0. The asm code operates on a byte at a time, xor'ing and subtracting from the previous byte.

The asm code would seem to leave the first byte of the buffer untouched.

Your C code moves an index and xors the four bytes pointed by that byte index with 0xC5. That code is reading three bytes too many and only affecting the lowest byte with the XOR.

Plus your for-loop starts at the front and works its way to the end - the opposite of your asm routine.

Assuming chars are byte-sized, then to mimic the asm routine, your subtraction step would be:

buffer[i] = buffer[i] - buffer[i-1];

which can be rewritten as:

buffer[i] -= buffer[i-1];

...assuming you fix your for-loop to go from the end-1 of the array to index 1.

You need to change buffer to type unsigned char, and change your for loop to:

for (i = count - 1; i > 0; i--)
{
    buffer[i] ^= xorkey;
    buffer[i] -= buffer[i - 1];
}

Note though that this code works on the file in 1024-byte chunks from the start, and then works on each chunk in reverse. If you want to work on the whole file in reverse, you'll need to start reading from the end of it, and have special handling for the first character in each chunk.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!