如何使用boost::hash获取文件内容哈希值

How to use boost::hash to get the file content hash?

本文关键字:哈希值 文件 hash 何使用 boost 获取      更新时间:2023-10-16

是否可以使用boost:hash函数生成像MD5一样固定长度的文件内容哈希?

有一个快速的解决方案吗?

如果不是,最简单的方法是什么?

不,Boost不实现MD5。使用加密/哈希库。

根据我的经验,cryptoc++是很好的。

OpenSSL实现了所有流行的摘要,下面是一个使用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具有这样的功能。至少现在: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;
}

生活例子