Reputation: 4938
Is there a way to modify a string literal in C++ from macro?
The reason for that is obfuscating code, particularly, 2 mutex wishes:
I know that primitive modifications like XOR or shifting cannot be enough for professional analysis, but they are good enough for me.
Upvotes: 0
Views: 279
Reputation: 137770
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.
Upvotes: 3
Reputation: 5459
You could create a macro that doesn't really do anything, but use the macro as a "marker" for a custom build step (simple script might do it) to obfuscate the strings prior to the preprocessor getting the source code.
Upvotes: 3