Hash Functions

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

Hash functions are a cryptographic one-way function used to digest data. Crypto++ includes a number of hash functions, including SHA-1, SHA-2 (SHA-224, SHA-256, SHA-384, and SHA-512), SHA-3, Tiger, WHIRLPOOL, RIPEMD-128, RIPEMD-256, RIPEMD-160, RIPEMD-320. In addition, MD5 is available in the Weak namespace.


The next several examples show you how to use MD5, SHA1 and filters. All hashes derive from HashTransformation so you can swap-in any hash simply by changing the declaration.

The SHA algorithm

SHA, or most other hash modules, is used like this:

byte digest[SHA::DIGESTSIZE];
SHA().CalculateDigest(digest, pbData, nDataLen);

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

SHA hash;
byte digest[SHA::DIGESTSIZE];

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

The MD5 algorithm

The example below uses the MD5 algorithm and saves the output in a hex encoded string. MD5 is on the weak and wounded algorithm list, so you must define CRYPTOPP_ENABLE_NAMESPACE_WEAK before including the header.

#include <md5.h>

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

CryptoPP::Weak::MD5 hash;
hash.CalculateDigest( digest, (const 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. A HexEncoder is attached to the hash filter so the binary digest is encoded in ASCII. A StringSink is attached to the hex encoder and it accumulates the output of the hex encoded digest.

SHA256 hash;
string message = "abcdefghijklmnopqrstuvwxyz";
string digest;
StringSource s(message, true, new HashFilter(hash, new HexEncoder(new StringSink(digest))));

cout << digest << endl;

The following takes a filename in argv[1] and hashes the file's contents.

SHA256 hash;
string digest;
FileSource f(argv[1], true, new HashFilter(hash, new HexEncoder(new StringSink(digest))));

cout << digest << endl;

Also see Pipelines on the Crypto++ wiki to explain why you don't have to delete the new HexEncoder or new StringSink.

Sample Programs

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