There has been some recent discussion here concerning how to save password information. In general, it is a Very Bad Idea(tm) to just store a password in an application, data file, INI file, registry, or anywhere but in volatile memory.
A better idea than trying to save a password is to save a "cryptological hash" of the password. Cryptographers call this type of hash a "digest". A digest function in this context is just a function that takes a block of text (called "the plaintext") and computes a checksum type number for that block. Cryptological digests have the properties that,
- It is highly unlikely that different input text will produce the same digest.
- It is very, very difficult if not totally impossible to get from the digest back to the input plaintext.
Programmers wishing to secure their password data can immediately compute the digest of the password, and then save that. When the user is prompted for a password, the digest of the input password candidate is computed, and this digest is compared against the stored digest. If they are equal, then the user has entered the correct password. Note that the programmer can post the stored hash value on a public web page or a billboard on the highway, and the security of his product is not compromised. He or she has no worries about someone with a hex editor digging out passwords.
Digests may also be used to verify that a message has been transmitted correctly, in a manner similar to cyclic redundancy checks.
A proven digest algorithm is "Message Digest Five" by Ron Rivest (Ron is the ‘R’ in RSA). It is described in Internet RFC 1321, "The MD5 Message-Digest Algorithm". A google search will provide hundreds of links to this RFC, I used the one I found here. This RFC includes a K&R style ‘C’ implementation of the MD5 algorithm. This implementation is a bit awkward to use, so I’ve wrapped it in a simple generic C++ class. The class is called
CMD5. It has only four interesting members:
CMD5(const char* plainText);
void setPlainText(const char* plainText);
const char* getMD5Digest();
To use the class, just set the plain text either in the constructor or with the
setPlainText member. The class calls a very slightly modified version of the RFC 1321 code to compute the digest, which is immediately available by calling
Here is some pseudo code showing how to use this class:
cout >> "Enter password:";
cin >> strUserEnteredPassword;
CMD5 md5((const char*)strUserEnteredPassword));
To use the class, you need these files:
- md5class.h and md5class.cpp - The
CMD5 C++ code.
- global.h, MD5.h, md5.c - Slightly modified versions of the RFC 1321 code.
These files are generic C++. The zip file includes a Win32 console app project that includes a main.cpp file. This little program runs the verification examples provided in the RFC. I use STL in this demo, but not in the class itself.