计算文件的md5值
std::string toHexString(const unsigned char* hash, size_t length) {
static const char* const lut = "0123456789abcdef";
std::string ret;
for (size_t i = 0; i < length; ++i) {
ret += lut[(hash[i] >> 4) & 0xf];
ret += lut[hash[i] & 0xf];
}
return ret;
}
std::string calculateFileMD5(const std::string& filePath) {
std::ifstream ifs(filePath, std::ifstream::binary);
if (!ifs) {
std::cout << "failed to open: " << filePath << std::endl;
return "";
}
unsigned char md5[MD5_DIGEST_LENGTH];
EVP_MD_CTX* mdctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(mdctx, EVP_md5(), NULL);
char buffer[1024];
while (ifs.read(buffer, sizeof(buffer))) {
EVP_DigestUpdate(mdctx, buffer, ifs.gcount());
}
ifs.close();
EVP_DigestFinal_ex(mdctx, md5, NULL);
EVP_MD_CTX_free(mdctx);
return toHexString(md5, MD5_DIGEST_LENGTH);
}