I trying to write function, for compile-time hide (obfuscate) text strings in the binary code. Purpose: to disable easy search and modify text messages with binary editor.
Algorithm is simple: convert chars within string to deltas
, i. e. string abcd
must be saved in the binary file as a\001\001\001
.
I wrote the following code, it works:
#include <string>
#include <stdio.h>
#include <string.h>
constexpr std::string str_encrypt(const char *str) {
std::string rc;
unsigned char x = 0, c;
while(c = *str++) {
rc.push_back(c - x);
x = c;
}
return rc;
}
std::string str_decrypt(const std::string &str) {
std::string rc;
unsigned char x = 0;
for(unsigned char c : str)
rc.push_back(x += c);
return rc;
}
const std::string hello(str_encrypt("Hello, world!"));
int main(int argc, char **argv) {
for(unsigned char c : hello)
printf("%d ", c);
putchar('\n');
printf("S=[%s]\n", str_decrypt(hello).c_str());
return 0;
}
But string still is not "encrypted" within binary file:
$ c++ -std=c++2b -O2 constexpr.cpp && strings a.out | grep Hello
Hello, world!
When I change constexpr
to consteval
, I see compilation error:
$ c++ -std=c++2b -O2 constexpr.cpp
constexpr.cpp:23:36: error: βstd::string{std::__cxx11::basic_string<char>::_Alloc_hider{((char*)(&<anonymous>.std::__cxx11::basic_string<char>::<anonymous>.std::__cxx11::basic_string<char>::<unnamed union>::_M_local_buf))}, 13, std::__cxx11::basic_string<char>::<unnamed union>{char [16]{'H', '\035', '\007', '\000', '\003', '\37777777675', '\37777777764', 'W', '\37777777770', '\003', '\37777777772', '\37777777770', '\37777777675', 0}}}β is not a constant expression
23 | const std::string hello(str_encrypt("Hello, world!"));
My question: Is possible to write such compile-time encryption? If so, please suggest, how to do.
My compiler: g++ (GCC) 12.2.1 20230201