简体   繁体   中英

String modification in C++ macro

Is there a way to modify a string literal in C++ from macro?

The reason for that is obfuscating code, particularly, 2 mutex wishes:

  1. I want to see literals as is in my source code, say, "password123".
  2. I want them to be mangled somehow before compilation to avoid including them in binaries.

I know that primitive modifications like XOR or shifting cannot be enough for professional analysis, but they are good enough for me.

您可以创建一个实际上没有做任何事情的宏,但可以将宏用作自定义构建步骤的“标记”(简单脚本可能会执行此操作),以在预处理器获取源代码之前混淆字符串。

You can use the macro to pass the string to a constexpr function which does the "encryption." Since C++14, constexpr is much easier to use.

// Similar to std::array, but with a member pointer as an accessor.
// It's complicated.
template< std::size_t length >
struct string_holder {
    char str[ length ];
    char const * ptr = str;
};

template< std::size_t length >
constexpr string_holder< length > encrypt( char const (& in)[ length ] ) {
    string_holder< length > result = {};
    for ( std::size_t i = 0; i != length - 1; ++ i ) {
        result.str[ i ] = in[ i ] ^ 1; // Do encryption here.
    }
    return result;
}

#define ENCRYPT( STR ) ( encrypt( STR ).ptr )

char const * const & s = ENCRYPT( "password123" );

http://coliru.stacked-crooked.com/a/3b6f6753d9f722cb

Note, s needs to be declared as a const& reference to take advantage of lifetime extension. You could also write auto const& s or auto &&s ; it would be the same. The current version of Clang does not allow s to be declared constexpr , but I believe this to be a bug.

Ideally , you could just write a user-defined literal like "password123"_encrypted . Unfortunately, progress on implementing the underlying language features for that is slow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM