Using the des class
The des class provides the hash method commonly used on unix and unix-like platforms for password encryption.
The des class inherits from the hash class and shares a common interface with the other hash classes: append() to feed in data, getHash() to retrieve the hash, getHashSize() to get the hash length in bytes, and clear() to reset. The isSupported() method can be used to determine if the hash algorithm is available on the current platform.
Unlike the other hash classes, the des class requires a 2-character salt from the set a-zA-Z0-9./. The salt must be set using setSalt() before calling getHash(). The getRequiredSaltSize() method returns the required salt size, which is always 2 for DES.
The output of getHash() is NULL-terminated printable ASCII, so the result can be used directly as a string.
The same data hashed with different salts will produce different hashes.
The following example hashes a string with one salt, clears and hashes a different string with the same salt, and then hashes the original string again with a different salt to illustrate the effect.
#include <rudiments/des.h>
#include <rudiments/charstring.h>
#include <rudiments/stdio.h>
int main(int argc, const char **argv) {
des h;
// check whether des is supported
if (!h.isSupported()) {
stdoutput.write("des is not supported\n");
return 1;
}
// set a 2-character salt
const byte_t *salt=(const byte_t *)"ab";
h.setSalt(salt,h.getRequiredSaltSize());
// hash some data
const char *data="hello world";
h.append((const byte_t *)data,charstring::getLength(data));
// print the hash (des output is printable ascii)
stdoutput.printf("des(\"%s\") = %s\n",data,(const char *)h.getHash());
// clear and hash different data
h.clear();
data="goodbye world";
h.append((const byte_t *)data,charstring::getLength(data));
stdoutput.printf("des(\"%s\") = %s\n\n",data,
(const char *)h.getHash());
// hash with a different salt
h.clear();
salt=(const byte_t *)"xy";
h.setSalt(salt,h.getRequiredSaltSize());
data="hello world";
h.append((const byte_t *)data,charstring::getLength(data));
stdoutput.printf("des(\"%s\") with salt \"xy\" = %s\n",
data,(const char *)h.getHash());
}