自定义字符串加密适用于某些字符串,但奇怪的是不适用于其他字符串?

问题描述 投票:0回答:1

目前正在开发 XorStr 的更强版本,并且也有兴趣出于纯粹的教育目的制作自己的版本,这就是为什么在下面提到的代码中我简化了函数中使用的实际算法,以更好地帮助调试这个奇怪的问题。然而,尽管进行了无数的更改,这些更改似乎确实影响了运行时加密和未加密的部分内容,但我对 C/C++ 这方面知识的缺乏确实使这一问题变得具有挑战性,所以我想我会在这里问。

实际问题:程序内部任何部分都完全唯一的两个字符串(我已验证)在编译后显示出不同的结果,似乎没有任何原因?

可重现示例:

#include <Windows.h>
#include <iostream>
#include <random>

template<size_t Size, int64_t Key, int32_t UniqueID, bool InlinedKey = true>
class ISE {
private:
    char StringData[Size];
    mutable char DecryptedData[Size];
    constexpr static int64_t XorKey = InlinedKey ? Key : 0;

    constexpr __forceinline char XorChar(char C, size_t I, size_t S) const {
        char KeyCalc1 = (char)((Key + I + S) % 0xFF);
        char KeyCalc2 = (char)((I + S) % 0xFF);
        
        char BaseCalc1 = C ^ KeyCalc1;
        BaseCalc1 = BaseCalc1 + KeyCalc1;

        return BaseCalc1 ^ KeyCalc2;
    }

public:
    constexpr ISE(const char(&Input)[Size]) : StringData{} {
        for (size_t i = 0; i < Size; ++i) {
            DecryptedData[i] = '\0';
            StringData[i] = XorChar(Input[i], i, Size);
        }
    }

    static const ISE& GetInstance(const char(&Input)[Size]) {
        static const ISE OutputInstance(Input);
        return OutputInstance;
    }

    const char* c_str(int64_t InputKey = XorKey) const {
        for (size_t i = 0; i < Size; ++i) {
            DecryptedData[i] = '\0'; //UXorChar(InputKey, StringData[i], i, Size);
        }
        return DecryptedData;
    }
};
#define UNIQUE_ID (__LINE__ * 0x100 + __COUNTER__)
#define _(Str, Key) (ISE<sizeof(Str), Key, UNIQUE_ID, true>::GetInstance(Str).c_str())

int main()
{
    printf(_("Hello", 0xDDDA2254D545));
    printf(_("Couldn't Allocate On Target Process, Contact Support!", 0xFFFA2254D545));
    return 1;
} //Important to Note the String is being left in the binary, and will likely appear encrypted when running because its just placing my ISE Initializer in the runtime executable (Which it should not be doing!)

这只是我能找到的留下字符串的示例之一,在该示例中,“Hello”在二进制文件中完全隐藏,但“无法在目标进程上分配,请联系支持人员!”不是?当在更大的项目上尝试这个时,情况会变得更糟,随机近 30% 的字符串似乎在编译时甚至没有被处理,我不知道为什么会这样。非常感谢任何和所有的帮助!

c++ constexpr
1个回答
0
投票

编译器生成加密字符串,直到它可以在模板实例化期间使用

XorChar
调用计算循环的结果,这对于大
Size
值来说很难做到。

当编译器可以时,它会在编译时生成结果加密字符串,因此不再需要您的源字符串。

当它达到某个阈值(取决于编译器,对于 MSVC 来说是 36)时,它放弃在编译时计算结果并开始实现一个函数,该函数将使用字符串的实际值实际调用,因此它有存放在某处。

您可能会在生成的代码中看到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.