Protecting passwords »
In some applications you'll need to supply a password to get access to features.
One of the most common uses is maybe server administration. Maybe you add an
HTML configuration interface for this task. The password needs to be stored somewhere
on the server to be matched with the entered password of an administrator. Storing
passwords in plain text is stupid. That's why we need some kind of irreversible encryption.
The MD5, Message Digest algorithm 5, is a hash function with a hash size of 128 bits.
This practically means we can make a 16 byte footprint of any data. Knowing this,
it's not hard to figure out that hashes can collide. This is not a practical
problem for password storing however.
The idea is to compare hashes instead of comparing the actual passwords.
MD5 implementation »
The MD5 algorithm was implemented by Peter Deutsch and can be found here.
Below is a helper function making it easier to use the algorithm in a C++ environment.
std::string hash_password(const std::string &password, const std::string &salt)
std::string pwd = password + salt;
md5_append(&pms, reinterpret_cast<const md5_byte_t*>(pwd.c_str()), pwd.length());
for (int i = 0; i < 4; ++i)
::sprintf(&d[i*8], "%08X", *reinterpret_cast<int*>(&hash[i*4]));
digest = d;
The salt variable is used to get around the fact that it is possible to create colliding hashes.
Using a salt will prevent someone with access to the password hashes to extract the actual
password with a brute force attack. The salt value should be something unique in
each application, and can have any value.
Note: This implementation does not prevent hackers from figuring out a password that will yield a valid hash if
they have access to the actual password hashes. Getting your actual password is however a bit harder.
To get better security one could replace the hash_password() function body by an SHA algorithm instead.