Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random text obfuscation algorithm failure

Tags:

c

obfuscation

I have been experimenting with a simple XOR-based text obfuscation algorithm. Supposedly, when the algorithm is run twice in a series, I should get back the original input - yet in my implementation that only happens sometimes. Here's my code, with some random text to demonstrate the problem:

#include <stdio.h>

void obfuscate(char *text) {
        char i = 0, p = 0;

        while (text[i] != 0) {
                text[i] = (text[i] ^ (char)0x41 ^ p) + 0xfe;

                p = i++;
        }
}


int main(int argc, char **argv) {
    char text[] = "Letpy,Mprm` Nssl'w$:0==!";

    printf("%s\n", text);

    obfuscate(text);

    printf("%s\n", text);

    obfuscate(text);

    printf("%s\n", text);

    return 0;
}

How can I fix this algorithm so that it is indeed its own inverse? Any suggestions to improve the level of obfuscation?

like image 616
thkala Avatar asked Apr 01 '11 19:04

thkala


4 Answers

I see two problems here:

  1. The operation + 0xfe is not its own inverse. If you remove it and leave only XORs, each byte will be restored to its original value as expected.

  2. A more subtle problem: Encrypting the text could create a zero byte, which will truncate the text because you use null-terminated strings. The best solution is probably to store the text length separately instead of null-terminating the encrypted text.

like image 142
interjay Avatar answered Oct 13 '22 20:10

interjay


You're doing more than just a simple XOR here (if you left it at text[i] = text[i] ^ (char)0x41 it would work; you could even leave in the ^ p if you want, but the + 0xfe breaks it).

Why do you want to use this kind of text obfuscation? Common methods of non-secure obfuscation are Base64 (needs separate encode and decode) and Rot13 (apply a second time to reverse).

like image 37
Jonathan Avatar answered Oct 13 '22 20:10

Jonathan


First, to decode

text[i] = (text[i] ^ (char)0x41 ^ p) + 0xfe;

you need its inverse function, that would be

text[i] = (text[i] - 0xfe) ^ (char)0x41 ^ p;

Second, char i will be able to work only with short strings, use int.

And last (and most important!), is that after such an "obfuscation" the string could get zero terminated before its original end, so you should also check its original length or ensure that you cannot get zeroes in the middle.

like image 33
ruslik Avatar answered Oct 13 '22 18:10

ruslik


Why "add +0xfe"? That is (at least one) source of your non-reversibility.

I see that you obfuscate it by using XOR of the previous text value p, which means that repeated letters will cause bouncing back and forth between the values.

like image 26
Andy Finkenstadt Avatar answered Oct 13 '22 20:10

Andy Finkenstadt