constexpr 是C++11新的概念,一个constexpr 函数可以返回一个const 量,当传递的参数都是const 型的时候
根据这个特性,我们对代码中硬编码的字符串进行加密就可以防止被一些人轻易逆向识破或修改
代码大致如下
(1)转换后的也应该放到全局的buffer
//enc_string_buffer 模板可以定制各种长度的字符串缓冲区
template< typename chType, int StrLen>
struct enc_string_buffer
{
chType pdata[StrLen + 1] = {};
int cchLen = StrLen;
operator chType*() const
{
return (chType*)(&pdata[0]);
}
};
//const_str_len 返回常量字符串的长度
template<typename chType>
constexpr int const_str_len(const chType* pString)
{
int Len = 0;
while (*pString)
{
Len++;
pString++;
}
return Len;
}
//算术符--异或
template<typename chType>
constexpr chType enc_xor(const chType ch, const chType key)
{
return ch ^ key;
}
//constEncode_StringBuf创建一个加密的缓冲区
template<typename chType, int StrLen, typename fnChEncOp>
constexpr enc_string_buffer<chType, StrLen> constEncode_StringBuf(const chType* pString, const chType* pKey, const int KeyLen, fnChEncOp chencodeFunc)
{
enc_string_buffer<chType, StrLen> ret;
int len = const_str_len(pString);
if (len > StrLen - 1)
len = StrLen - 1;
for (int xx = 0; xx < len; xx++)
ret.pdata[xx] = chencodeFunc(pString[xx], pKey[xx % KeyLen]);
return ret;
}
typedef char(*pfn_enc_func_type)(const char ch, const char key);
typedef wchar_t(*pfn_enc_func_typeW)(const wchar_t ch, const wchar_t key);
#define DEC_ENC_STR_XORA(NAME,TEXT,KEY,KEYLEN)\
constexpr enc_string_buffer<char,sizeof((TEXT))> NAME=constEncode_StringBuf<char,sizeof((TEXT)),pfn_enc_func_type>((TEXT),(KEY),(KEYLEN),enc_xor<char>)
#define DEC_ENC_STR_XORW(NAME,TEXT,KEY,KEYLEN)\
constexpr enc_string_buffer<wchar_t ,sizeof((TEXT))/sizeof(wchar_t)> NAME=constEncode_StringBuf<wchar_t ,sizeof((TEXT))/sizeof(wchar_t),pfn_enc_func_typeW>((TEXT),(KEY),(KEYLEN),enc_xor<wchar_t>)
(2)利用宏定义一个加密缓冲区
DEC_ENC_STR_XORA (g_kill1, "Kill1", "Hello", 5);
则全局将存在一个加密的缓冲区,这个缓冲区将在编译前计算好
(3)注意宏中的是constexpr
(4)constexpr函数请放到头文件中,其在release版本下不存在代码