Is it possible to use boost:hash function to generate a file content hash with fixed length like MD5?
Is there a quick solution for this?
If not, what is the simplest way?
Is it possible to use boost:hash function to generate a file content hash with fixed length like MD5?
Is there a quick solution for this?
If not, what is the simplest way?
No, Boost doesn't implement MD5. Use a crypto/hash library for this.
CryptoC++ is nice in my experience.
OpenSSL implements all the popular digests, here's a sample that uses OpenSSL:
Live On Coliru
#include <openssl/md5.h>
#include <iostream>
#include <iomanip>
// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md) {
for(unsigned i=0; i <MD5_DIGEST_LENGTH; i++) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(md[i]);
}
}
#include <string>
#include <vector>
#include <fstream>
int main(int argc, char *argv[]) {
using namespace std;
vector<string> const args(argv+1, argv+argc);
for (auto& fname : args) {
MD5_CTX ctx;
MD5_Init(&ctx);
ifstream ifs(fname, std::ios::binary);
char file_buffer[4096];
while (ifs.read(file_buffer, sizeof(file_buffer)) || ifs.gcount()) {
MD5_Update(&ctx, file_buffer, ifs.gcount());
}
unsigned char digest[MD5_DIGEST_LENGTH] = {};
MD5_Final(digest, &ctx);
print_md5_sum(digest);
std::cout << "\t" << fname << "\n";
}
}
boot has such functionality. At lest now: https://www.boost.org/doc/libs/master/libs/uuid/doc/uuid.html
#include <iostream>
#include <algorithm>
#include <iterator>
#include <boost/uuid/detail/md5.hpp>
#include <boost/algorithm/hex.hpp>
using boost::uuids::detail::md5;
std::string toString(const md5::digest_type &digest)
{
const auto charDigest = reinterpret_cast<const char *>(&digest);
std::string result;
boost::algorithm::hex(charDigest, charDigest + sizeof(md5::digest_type), std::back_inserter(result));
return result;
}
int main ()
{
std::string s;
while(std::getline(std::cin, s)) {
md5 hash;
md5::digest_type digest;
hash.process_bytes(s.data(), s.size());
hash.get_digest(digest);
std::cout << "md5(" << s << ") = " << toString(digest) << '\n';
}
return 0;
}
Live Example