Hash Functions

From Crypto++ Wiki
(Redirected from Hashing)
Jump to: navigation, search

Hash functions provide a way of creating a digital fingerprint for data. The function substitutes and transposes (chops or mixes) the data to create the fingerprint, often called a hash value or digest.


/* fill out */


The SHA algorithm

SHA (or any other hash module) is used like this:

SHA().CalculateDigest(pbOutputBuffer, pbData, nDataLen);
// pbOutputBuffer must be SHA::DIGESTSIZE bytes in length

or, if you have data that's made up of multiple pieces:

SHA hash;
hash.Update(pbData1, nData1Len);
hash.Update(pbData2, nData2Len);
hash.Update(pbData3, nData3Len);

The MD5 algorithm

Shows one way of using the MD5 algorithm and saves the output in a hex-encoded string:

CryptoPP::MD5 hash;
byte digest[ CryptoPP::MD5::DIGESTSIZE ];
std::string message = "abcdefghijklmnopqrstuvwxyz";

hash.CalculateDigest( digest, (byte*) message.c_str(), message.length() );

CryptoPP::HexEncoder encoder;
std::string output;
encoder.Attach( new CryptoPP::StringSink( output ) );
encoder.Put( digest, sizeof(digest) );

std::cout << output << std::endl;

Hashing Using Filters

This is an example of hashing using filters. Note that the output is encoded as hex which is why the output buffer must be two times the size of the MD5 digest.

MD5 hash;
byte buffer[2 * MD5::DIGESTSIZE]; // Output size of the buffer
FileSource f(argv[1], true,
             new HashFilter(hash,
             new HexEncoder(new ArraySink(buffer,2 * MD5::DIGESTSIZE))));

cout << string((const char*)buffer,2 * MD5::DIGESTSIZE)  << endl;

Sample Programs

SymmetricCipher.zip - Exercises Symmetric Ciphers using the Cipher's Default Key Length and Default IV