C++: How to encrypt strings at compile time?

前端 未结 10 1285
北荒
北荒 2020-12-18 21:40

I want to hide some strings in my .exe so people can\'t simply just open the .exe and look at all the strings there. I don\'t care about the strength of the encrypting metho

10条回答
  •  渐次进展
    2020-12-18 22:37

    This probably doesn't apply to the ancient compiler of the question, but on more more modern C++ implementations, we can use a string literal operator template that's declared constexpr to implement compile-time obfuscation. For this, I've used GCC 7.2.0 with -std=c++17 (and a full set of warning options, of course).

    Firstly, we define a type to hold our obfuscated string data, with a conversion operator to produce a plaintext string on demand:

    #include 
    #include 
    
    template
    static const Char SECRET = 0x01;
    
    template::size_type Length>
    struct obfuscated_string
    {
        using String = std::basic_string;
    
        const std::array storage;
    
        operator String() const
        {
            String s{storage.data(), Length};
            for (auto& c: s)
                c ^= SECRET;
            return s;
        }
    };
    

    Now, the literal operator template to convert a source-code literal to an obfuscated string:

    template
    constexpr obfuscated_string operator ""_hidden()
    {
        return { { (STR ^ SECRET)... } };
    }
    

    To demonstrate:

    #include 
    int main()
    {
        static const auto message = "squeamish ossifrage"_hidden;
        std::string plaintext = message;
        std::cout << plaintext << std::endl;
    }
    

    We can inspect the object code with the strings program. The binary doesn't contain squeamish ossifrage anywhere; instead it has rptd`lhri!nrrhgs`fd. I've confirmed this with a range of optimisation levels to demonstrate that the conversion back to std::string doesn't get pre-computed, but I advise you conduct your own tests whenever you change compiler and/or settings.

    (I'm deliberately ignoring whether this is an advisable thing to do - merely presenting a technical working solution).

提交回复
热议问题