编译时字符串加密

Compile-time string encryption

本文关键字:加密 字符串 编译      更新时间:2023-10-16

我不希望逆向工程师在我的应用程序中读取硬编码字符串的纯文本。简单的解决方案是使用简单的异或加密。问题是我需要一个转换器,在我的应用程序中,它看起来像这样:

//Before (unsecure)
char * cString = "Helllo Stackoverflow!";
//After (secure)
char * cString = XStr( 0x06, 0x15, 0x9D, 0xD5FBF3CC, 0xCDCD83F7, 0xD1C7C4C3, 0xC6DCCEDE, 0xCBC2C0C7, 0x90000000 ).c();

是否有可能通过使用像

这样的结构来维护干净的代码?
//Before (unsecure)
char * cString = "Helllo Stackoverflow!";
//After (secure)
char * cString = CRYPT("Helllo Stackoverflow!");

它也应该适用于相当长的字符串(1000个字符?: -))。提前谢谢大家

确实存在完美的解决方案,这就是。

我也认为这是不可能的,即使它很简单,人们写的解决方案,你需要一个自定义工具扫描构建文件,扫描字符串和加密字符串,像那样,这还不错,但我想要一个包,从Visual Studio编译,这是可能的!

你需要的是C++ 11 (Visual Studio 2015 Update 1开箱即用)

这个新命令constexpr

神奇的事情发生了

神奇的发生在这个#define

#define XorString( String ) ( CXorString<ConstructIndexList<sizeof( String ) - 1>::Result>( String ).decrypt() )

它不会在编译时解密XorString,只会在运行时解密,但它只会在编译时加密字符串,所以字符串不会出现在可执行文件

printf(XorString( "this string is hidden!" ));

它将打印出"this string is hidden!",但你不会在可执行文件中找到它作为字符串!,自己用Microsoft Sysinternals Strings程序下载链接检查:https://technet.microsoft.com/en-us/sysinternals/strings.aspx

完整的源代码相当大,但可以很容易地包含在一个头文件中。但也是相当随机的,所以加密的字符串输出总是在每次新的编译中改变,种子是根据它编译所花费的时间而改变的,非常可靠,完美的解决方案。

创建名为XorString.h的文件

#pragma once
//-------------------------------------------------------------//
// "Malware related compile-time hacks with C++11" by LeFF   //
// You can use this code however you like, I just don't really //
// give a shit, but if you feel some respect for me, please //
// don't cut off this comment when copy-pasting... ;-)       //
//-------------------------------------------------------------//
////////////////////////////////////////////////////////////////////
template <int X> struct EnsureCompileTime {
    enum : int {
        Value = X
    };
};
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
//Use Compile-Time as seed
#define Seed ((__TIME__[7] - '0') * 1  + (__TIME__[6] - '0') * 10  + 
              (__TIME__[4] - '0') * 60   + (__TIME__[3] - '0') * 600 + 
              (__TIME__[1] - '0') * 3600 + (__TIME__[0] - '0') * 36000)
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
constexpr int LinearCongruentGenerator(int Rounds) {
    return 1013904223 + 1664525 * ((Rounds> 0) ? LinearCongruentGenerator(Rounds - 1) : Seed & 0xFFFFFFFF);
}
#define Random() EnsureCompileTime<LinearCongruentGenerator(10)>::Value //10 Rounds
#define RandomNumber(Min, Max) (Min + (Random() % (Max - Min + 1)))
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
template <int... Pack> struct IndexList {};
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
template <typename IndexList, int Right> struct Append;
template <int... Left, int Right> struct Append<IndexList<Left...>, Right> {
    typedef IndexList<Left..., Right> Result;
};
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
template <int N> struct ConstructIndexList {
    typedef typename Append<typename ConstructIndexList<N - 1>::Result, N - 1>::Result Result;
};
template <> struct ConstructIndexList<0> {
    typedef IndexList<> Result;
};
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
const char XORKEY = static_cast<char>(RandomNumber(0, 0xFF));
constexpr char EncryptCharacter(const char Character, int Index) {
    return Character ^ (XORKEY + Index);
}
template <typename IndexList> class CXorString;
template <int... Index> class CXorString<IndexList<Index...> > {
private:
    char Value[sizeof...(Index) + 1];
public:
    constexpr CXorString(const char* const String)
    : Value{ EncryptCharacter(String[Index], Index)... } {}
    char* decrypt() {
        for(int t = 0; t < sizeof...(Index); t++) {
            Value[t] = Value[t] ^ (XORKEY + t);
        }
        Value[sizeof...(Index)] = '';
        return Value;
    }
    char* get() {
        return Value;
    }
};
#define XorS(X, String) CXorString<ConstructIndexList<sizeof(String)-1>::Result> X(String)
#define XorString( String ) ( CXorString<ConstructIndexList<sizeof( String ) - 1>::Result>( String ).decrypt() )
////////////////////////////////////////////////////////////////////

更新代码如下,这是一个更好的版本,支持char和wchar_t字符串!

#pragma once
#include <string>
#include <array>
#include <cstdarg>
#define BEGIN_NAMESPACE( x ) namespace x {
#define END_NAMESPACE }
BEGIN_NAMESPACE(XorCompileTime)
constexpr auto time = __TIME__;
constexpr auto seed = static_cast< int >(time[7]) + static_cast< int >(time[6]) * 10 + static_cast< int >(time[4]) * 60 + static_cast< int >(time[3]) * 600 + static_cast< int >(time[1]) * 3600 + static_cast< int >(time[0]) * 36000;
// 1988, Stephen Park and Keith Miller
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
// with 32-bit math and without division
template < int N >
struct RandomGenerator
{
private:
    static constexpr unsigned a = 16807; // 7^5
    static constexpr unsigned m = 2147483647; // 2^31 - 1
    static constexpr unsigned s = RandomGenerator< N - 1 >::value;
    static constexpr unsigned lo = a * (s & 0xFFFF); // Multiply lower 16 bits by 16807
    static constexpr unsigned hi = a * (s >> 16); // Multiply higher 16 bits by 16807
    static constexpr unsigned lo2 = lo + ((hi & 0x7FFF) << 16); // Combine lower 15 bits of hi with lo's upper bits
    static constexpr unsigned hi2 = hi >> 15; // Discard lower 15 bits of hi
    static constexpr unsigned lo3 = lo2 + hi;
public:
    static constexpr unsigned max = m;
    static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
};
template <>
struct RandomGenerator< 0 >
{
    static constexpr unsigned value = seed;
};
template < int N, int M >
struct RandomInt
{
    static constexpr auto value = RandomGenerator< N + 1 >::value % M;
};
template < int N >
struct RandomChar
{
    static const char value = static_cast< char >(1 + RandomInt< N, 0x7F - 1 >::value);
};
template < size_t N, int K, typename Char >
struct XorString
{
private:
    const char _key;
    std::array< Char, N + 1 > _encrypted;
    constexpr Char enc(Char c) const
    {
        return c ^ _key;
    }
    Char dec(Char c) const
    {
        return c ^ _key;
    }
public:
    template < size_t... Is >
    constexpr __forceinline XorString(const Char* str, std::index_sequence< Is... >) : _key(RandomChar< K >::value), _encrypted{ enc(str[Is])... }
    {
    }
    __forceinline decltype(auto) decrypt(void)
    {
        for (size_t i = 0; i < N; ++i) {
            _encrypted[i] = dec(_encrypted[i]);
        }
        _encrypted[N] = '';
        return _encrypted.data();
    }
};
//--------------------------------------------------------------------------------
//-- Note: XorStr will __NOT__ work directly with functions like printf.
//         To work with them you need a wrapper function that takes a const char*
//         as parameter and passes it to printf and alike.
//
//         The Microsoft Compiler/Linker is not working correctly with variadic 
//         templates!
//  
//         Use the functions below or use std::cout (and similar)!
//--------------------------------------------------------------------------------
static auto w_printf = [](const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vprintf_s(fmt, args);
    va_end(args);
};
static auto w_printf_s = [](const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vprintf_s(fmt, args);
    va_end(args);
};
static auto w_sprintf = [](char* buf, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vsprintf(buf, fmt, args);
    va_end(args);
};
static auto w_sprintf_ret = [](char* buf, const char* fmt, ...) {
    int ret;
    va_list args;
    va_start(args, fmt);
    ret = vsprintf(buf, fmt, args);
    va_end(args);
    return ret;
};
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vsprintf_s(buf, buf_size, fmt, args);
    va_end(args);
};
static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
    int ret;
    va_list args;
    va_start(args, fmt);
    ret = vsprintf_s(buf, buf_size, fmt, args);
    va_end(args);
    return ret;
};
//Old functions before I found out about wrapper functions.
//#define XorStr( s ) ( XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char >( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ).decrypt() )
//#define XorStrW( s ) ( XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t >( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ).decrypt() )
//Wrapper functions to work in all functions below
#define XorStr( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
#define XorStrW( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()
END_NAMESPACE

这个博客提供了一个c++编译时字符串散列的解决方案。我想原理是一样的。遗憾的是,您必须为每个字符串长度创建一个唯一的宏。

我的首选解决方案:

// some header
extern char const* const MyString;
// some generated source
char const* const MyString = "aioghaiogeubeisbnuvs";

然后使用您喜欢的脚本语言生成这个源文件,其中存储"加密"资源。

这是一个迟来的答案,但我相信有更好的解决方案。

请参考此处公认的答案。

基本上,它展示了如何使用ADVobfuscator库来混淆字符串,就像这样简单:

#include "MetaString.h"
using namespace std;
using namespace andrivet::ADVobfuscator;
void Example()
{
    /* Example 1 */
    // here, the string is compiled in an obfuscated form, and
    // it's only deobfuscated at runtime, at the very moment of its use
    cout << OBFUSCATED("Now you see me") << endl;
    /* Example 2 */
    // here, we store the obfuscated string into an object to
    // deobfuscate whenever we need to
    auto narrator = DEF_OBFUSCATED("Tyler Durden");
    // note: although the function is named `decrypt()`, it's still deobfuscation
    cout << narrator.decrypt() << endl;
}

我认为你必须做一些事情,就像使用gettext (i18n):

  • 使用像CRYPT一样的宏。
  • 使用一个解析器,当它找到crypt时将加密字符串。
  • 写一个解密的函数,由你的宏调用。

对于gettext,使用_()宏,该宏用于生成所需的字符串字典并调用gettext函数。

顺便说一下,您还必须管理i18n:),您将需要这样的内容:

_CRYPT_()
_CRYPT_I18N_()

你必须用你的构建系统来管理它,使它可维护。我用gettext…

My two cents

如果您愿意使用c++ 11的特性,可变模板可用于对可变长度字符串进行编译时加密,示例如下:

如果人们对简单的字符串加密感兴趣。我写了一个代码示例,描述字符串的自我解密和标记使用一个宏。提供了一个外部加密代码来修补二进制文件(因此在程序编译后对字符串进行加密)。字符串在内存中每次解密一个。

http://www.sevagas.com/?String-encryption-using-macro-and

这不会阻止带有调试器的反向器最终找到字符串,但它会阻止可执行字符串列表和内存转储。

我无法编译,编译器抛出无数错误,我正在寻找快速字符串加密的其他解决方案,并发现了这个小玩具https://www.stringencrypt.com(并不难,谷歌字符串加密关键字的第一结果)。

它是这样工作的:

  1. 输入标签名sString
  2. 您输入字符串内容
  3. 您点击加密
  4. 它接受字符串并对其加密
  5. 用c++生成解密源代码(支持许多其他语言)
  6. 你把这个片段粘贴到你的代码

示例字符串"StackOverflow is awesome!",输出代码(每次它都会生成略有不同的代码)。它支持ANSI (char)和UNICODE (wchar_t)类型的字符串

ANSI输出:

// encrypted with https://www.stringencrypt.com (v1.1.0) [C/C++]
// sString = "StackOverflow is awesome!"
unsigned char sString[26] = { 0xE3, 0x84, 0x2D, 0x08, 0xDF, 0x6E, 0x0B, 0x87,
                              0x51, 0xCF, 0xA2, 0x07, 0xDE, 0xCF, 0xBF, 0x73,
                              0x1C, 0xFC, 0xA7, 0x32, 0x7D, 0x64, 0xCE, 0xBD,
                              0x25, 0xD8 };
for (unsigned int bIFLw = 0, YivfL = 0; bIFLw < 26; bIFLw++)
{
        YivfL = sString[bIFLw];
        YivfL -= bIFLw;
        YivfL = ~YivfL;
        YivfL = (((YivfL & 0xFF) >> 7) | (YivfL << 1)) & 0xFF;
        YivfL ++;
        YivfL ^= 0x67;
        YivfL = (((YivfL & 0xFF) >> 6) | (YivfL << 2)) & 0xFF;
        YivfL += bIFLw;
        YivfL += 0x0F;
        YivfL = ((YivfL << 4) | ( (YivfL & 0xFF) >> 4)) & 0xFF;
        YivfL ^= 0xDA;
        YivfL += bIFLw;
        YivfL ++;
        sString[bIFLw] = YivfL;
}
printf(sString);
UNICODE输出:

// encrypted with https://www.stringencrypt.com (v1.1.0) [C/C++]
// sString = "StackOverflow is awesome!"
wchar_t sString[26] = { 0x13A6, 0xA326, 0x9AA6, 0x5AA5, 0xEBA7, 0x9EA7, 0x6F27, 0x55A6,
                        0xEB24, 0xD624, 0x9824, 0x58A3, 0x19A5, 0xBD25, 0x62A5, 0x56A4,
                        0xFC2A, 0xC9AA, 0x93AA, 0x49A9, 0xDFAB, 0x9EAB, 0x9CAB, 0x45AA,
                        0x23CE, 0x614F };
for (unsigned int JCBjr = 0, XNEPI = 0; JCBjr < 26; JCBjr++)
{
        XNEPI = sString[JCBjr];
        XNEPI -= 0x5D75;
        XNEPI = (((XNEPI & 0xFFFF) >> 14) | (XNEPI << 2)) & 0xFFFF;
        XNEPI = ~XNEPI;
        XNEPI -= 0xA6E5;
        XNEPI ^= JCBjr;
        XNEPI = (((XNEPI & 0xFFFF) >> 10) | (XNEPI << 6)) & 0xFFFF;
        XNEPI --;
        XNEPI ^= 0x9536;
        XNEPI += JCBjr;
        XNEPI = ((XNEPI << 1) | ( (XNEPI & 0xFFFF) >> 15)) & 0xFFFF;
        sString[JCBjr] = XNEPI;
}
wprintf(sString);

现在我知道这可能不是完美的解决方案,但它适用于我和我的编译器