C++基于boost实现 获取文件或者字符串md5

  • Post author:
  • Post category:其他




C++基于boost实现 获取文件或者字符串md5

  • c++11
  • boost 1.66版本以上
#include <iostream>
#include <fstream>
#include <boost/algorithm/hex.hpp>
#include <boost/uuid/detail/md5.hpp>

bool getMd5(std::string& str_md5, const char* const buffer, size_t buffer_size)
{
    if (buffer == nullptr)
    {
        return false;
    }
    boost::uuids::detail::md5 boost_md5;
    boost_md5.process_bytes(buffer, buffer_size);
    boost::uuids::detail::md5::digest_type digest;
    boost_md5.get_digest(digest);
    const auto char_digest = reinterpret_cast<const char*>(&digest);
    str_md5.clear();
    boost::algorithm::hex(char_digest, char_digest + sizeof(boost::uuids::detail::md5::digest_type), std::back_inserter(str_md5));
    return true;
}

std::string getMd5(const std::string &filename)
{
    std::string str_md5;
    std::ifstream is(filename, std::ifstream::binary);
    if (is) {
        // get length of file:
        is.seekg(0, is.end);
        int length = is.tellg();
        is.seekg(0, is.beg);

        // allocate memory:
        char* buffer = new char[length];
        // read data as a block:
        is.read(buffer, length);
        is.close();

        getMd5(str_md5, buffer, length);
        delete[] buffer;
    }
    return str_md5;
}



版权声明:本文为stallion5632原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。