Introduction
MetaEncrypt is a very simple C++ template class that encrypts literal strings at compile time.
Background
Many years ago with a couple of friends we made a plug-in for a well-known vector animation application. When the pug-in was working and tested, we started
designing the installation/deployment part. Supposedly the user would download a demo, play with it, and at some point would go to a secure server, pay,
and download the complete version. So, I had to hardcode the secure server URL. That wasn’t a big deal, but with our current improvised infrastructure,
I wanted to avoid as many as possible all chances of unauthorized accesses.
So I started to think what could be a good idea to have only one or two strings encrypted in the binary executable without any expensive deployment/technique.
Also I didn’t want to have a post-build event with an external application, that always end up being another problem with its own code, bugs, and maintenance.
It shouldn’t have to be an ultra secure encryption method, just something that will leave the common user
out of the game .
At some point, it came to me the idea to encrypt strings at compile time, and at that point I was reading “C++ Template Metaprogramming” by David Abrahams,
so those two lines crossed. With not so much effort I had this C++ template that encrypts string literals using the
^
operator at compile time.
This is the core of the idea:
template <char c,int car_num>
class EncryptChar
{
public:
enum
{
v = c ^ car_num
};
};
and with the following defines:
#define SEED 123456789
#define Ec(c) EncryptChar<c, SEED >>::v
you could do something like this:
static const char someEncryptedString[] =
{
Ec('Y'),
Ec('E'),
Ec('S')
};
the Ec
macro will expand for each character to create a template value that gets encrypted with the seed. Simple.
Using the Code
We already created an encrypted string ('YES'), so you will need to decrypt it at run-time, you could do it like this:
std::string decryptedString;
decryptedString = Decryptor::DecryptString(someEncryptedString,sizeof(someEncryptedString));
and just use it.
Points of Interest
In the project mentioned at the beginning of the article, I ended up using a little more elaborate encryption including other values in the seed,
and some other template metaprogramming tips, but basically the idea was the same.
I’m not involved with the plug-in project for now, but it went very good. There were no serious security issues with the server and no complaints from
the client. So after all these years, I decided to share this idea with you, that ended up to be a very interesting and simple solution.