Mam szablon klasy, która umożliwia szyfrowanie stringów w czasie kompilacji:
#ifndef ENCRYPTEDSTRING_H_INCLUDED
#define ENCRYPTEDSTRING_H_INCLUDED
#include "CompileTimeRandom.h"
template <unsigned int...> struct IndexList {};
template <typename IndexList, unsigned int Right> struct Append;
template <unsigned int... Left, unsigned int Right> struct Append<IndexList<Left...>, Right> { typedef IndexList<Left..., Right> Result; };
template <unsigned int N> struct Indexes { typedef typename Append<typename Indexes<N - 1>::Result, N - 1>::Result Result; };
template <> struct Indexes<0> { typedef IndexList<> Result; };
const char EncryptCharKey = COMPILETIME_RANDOM(0, 0xFF);
constexpr char EncryptChar(const char c, const unsigned int i) { return c ^ (EncryptCharKey + i); }
template <typename IndexList> struct EncryptedString;
template <unsigned int... I> struct EncryptedString< IndexList<I...>>
{
public:
constexpr inline EncryptedString(const char* const str) : buffer({ EncryptChar(str[I], I)...}), isEncrypted(true) { }
char* Decrypt()
{
if(!isEncrypted) return buffer;
for(volatile unsigned int t = 0; t < sizeof...(I); t++)
buffer[t] = buffer[t] ^ (EncryptCharKey + t);
buffer[sizeof...(I)] = '\0';
isEncrypted = false;
return buffer;
}
private:
char buffer[sizeof...(I) + 1];
bool isEncrypted;
};
#define ENCRYPT(str) EncryptedString<Indexes<sizeof(str) - 1>::Result>(str).Decrypt()
#endif // ENCRYPTEDSTRING_H_INCLUDED
Z nie wiadomych mi przyczyn szyfrowanie nie zawsze odbywa się w czasie kompilacji, przykładowo fragment kodu poniżej działa poprawnie:
#include "EncryptedString.h"
#include <string>
using namespace std;
int main()
{
string str = ENCRYPT("1234567890");
}
Ale gdy już spróbuje tak:
#include "EncryptedString.h"
#include <string>
using namespace std;
class Test
{
static string Str;
};
string Test::Str = ENCRYPT("ABCDEFGH");
int main()
{
string str = ENCRYPT("12345678");
}
To szyfrowanie nie działa, oba stringi można odczytać z pliku exe zwykłym notatnikiem. Zauważyłem że dzieje się tak tylko wtedy kiedy oba szyfrowane stringi mają jednakową długość, kiedy są różnej długości szyfrowanie odbywa się w czasie kompilacji. Czym to może być spowodowane?