Hash Functions

From Crypto++ Wiki
Jump to navigation Jump to search

Hash functions are a cryptographic one-way function used to digest data. Crypto++ includes a number of hash functions, including BLAKE2, Keccak, SHA-1, SHA-2, SHA-3, SHAKE, SM3, Tiger, WHIRLPOOL, and RIPEMD. In addition, MD5 is available in the Weak namespace.

If you want to add a hash to the library, then see Adding a Hash.

Examples

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:

using namespace CryptoPP;
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);
hash.Final(digest);

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.

#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <md5.h>

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

Weak::MD5 hash;
hash.CalculateDigest( digest, (const byte*)message.c_str(), message.length() );

HexEncoder encoder;
std::string output;

encoder.Attach( new StringSink( output ) );
encoder.Put( digest, sizeof(digest) );
encoder.MessageEnd();

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.

using namespace CryptoPP;

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.

using namespace CryptoPP;

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.

Downloads

No downloads available.