如何使用boost :: hash来获取文件内容的哈希值? [英] How to use boost::hash to get the file content hash?
本文介绍了如何使用boost :: hash来获取文件内容的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用boost:hash函数生成固定长度的文件内容哈希(如MD5)?
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?
推荐答案
否,Boost不实现MD5.为此使用加密/哈希库.
No, Boost doesn't implement MD5. Use a crypto/hash library for this.
根据我的经验,CryptoC ++很不错.
CryptoC++ is nice in my experience.
OpenSSL实现了所有流行的摘要,这是一个使用OpenSSL的示例:
OpenSSL implements all the popular digests, here's a sample that uses OpenSSL:
#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";
}
}
这篇关于如何使用boost :: hash来获取文件内容的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文