views:

450

answers:

5

I'd like to obscure strings at compile time. I know it can be done in other preprocessors but I haven't found a way to do this with the C preprocessor.

A: 

No, the C preprocessor does not have the capability to index strings as you suggest.

Out of curiosity, what other preprocessors have you used that can do this?

Greg Hewgill
+1  A: 

No, the C pre-processor cannot process strings character by character.

Did you have identifiers or strings in mind, anyway? You can do a lot with identifiers with fixed mappings (that is, if you know name1 appears, you can provide a fixed mapping to xq23), but you cannot algorithmically find identifiers and then create a mapping for them.

Jonathan Leffler
A: 

No, I can't think of any way of doing it with the preprocessor.

This related question might help you though: How to hide a string in binary code?

therefromhere
+2  A: 

Well, you can do it, but it's ugly.

#define ENCODE_STRING_14(str) {\
   str[0] ^ 0x020,\
   str[1] ^ 0x020,\
   str[2] ^ 0x020,\
   str[3] ^ 0x020,\
   str[4] ^ 0x020,\
   str[5] ^ 0x020,\
   str[6] ^ 0x020,\
   str[7] ^ 0x020,\
   str[8] ^ 0x020,\
   str[9] ^ 0x020,\
   str[10] ^ 0x020,\
   str[11] ^ 0x020,\
   str[12] ^ 0x020,\
   '\0'\
   }

void Decode( char *str, int length )
{
    for( int i = 0; i < length - 1; ++i )
    {
     str[i] ^= 0x20;
    }
}

char hello[] = ENCODE_STRING_14("Hello, World!");

int main()
{
    printf("%s\n", hello);
    Decode( hello, 14 );
    printf("%s\n", hello);
    return 0;
}

Compiled with optimizations in VS2005, the string is stored in the executable as "hELLO\x0C\0wORLD\x01". Now, obviously, xor with 0x20 isn't a good function to hide your string. And, of course, you'd have to #define a macro for each string length.

Obviously, this isn't the best solution. C++ template metaprogramming would be a better fit. You could also write all of your strings in a separate machine readable file, and write a separate program that parses that, obscures the strings in whatever way you see fit and outputs it all into .h/.c. Both of those are better solutions than this.

Geerad
A: 

Yes!

See my answer here.

Dmitriy