Hash File Using POCO

This is the first time I have had to create MD5 hashes for files in C++. I did find a library called POCO that has some very handy classes for doing this. I didn’t want to copy and paste code from work, so I created this simple example for hashing a single file and outputting the MD5 hash in a hex encoded string.

The hashing uses a chunk size of 1 MiB changes so the whole file is not loaded at once.

I will soon create another post on how to do this in Qt5 and post it then, updating this post with the link.

Check out the open source POCO C++ libraries at pocoproject.org/. There are downloads for Windows. For Linux, you may be able to get packages from the main repositories for your distro.

#include <iostream>
#include <fstream>
#include <Poco/DigestStream.h>
#include <Poco/MD5Engine.h>

int main(int argc, char** argv)
	Poco::MD5Engine md5;

	std::ifstream ifHash("../DSC_0002.JPG", std::ios::binary);
	if (ifHash.is_open())
		Poco::DigestInputStream isMd5(md5, ifHash);
		size_t bufSize = 0x100000;
		char* buf = new char[bufSize];

		isMd5.read(buf, bufSize);
		while ( (isMd5.rdstate() && std::ifstream::failbit) == 0 )
			isMd5.read(buf, bufSize);

		if ( (isMd5.rdstate() && std::ifstream::eofbit) != 0)
			std::string digest;
			digest = Poco::DigestEngine::digestToHex(md5.digest());
			std::cout << digest.c_str() << std::endl;

		delete [] buf;
This entry was posted in C++, Cryptography and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *