Is the C preprocessor able to process strings char by char?

让人想犯罪 __ 提交于 2019-12-24 15:27:00

问题


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.


回答1:


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.




回答2:


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.




回答3:


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?




回答4:


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?



来源:https://stackoverflow.com/questions/1381818/is-the-c-preprocessor-able-to-process-strings-char-by-char

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