如何在C ++中可移植地计算sha1哈希? [英] How to portably compute a sha1 hash in C++?

查看:68
本文介绍了如何在C ++中可移植地计算sha1哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是计算一个缓冲区或多个缓冲区的 SHA1 哈希一个C ++程序.

The objective is to compute the SHA1 hash of a buffer or multiple buffers as part of a C++ program.

推荐答案

我不确定使用boost的UUID的那个是否会正确地将哈希值的前导零(您的字符串应始终具有相同的长度afaik),所以这里是上面示例的简化版本可以做到这一点:

I'm not sure whether the one using boost's UUID will do leading zeros in hash values correctly (your string should always have the same length afaik), so here's a simplified version of the example above which will do that:

#include <cstdio>
#include <string>
#include <boost/uuid/sha1.hpp>

std::string get_sha1(const std::string& p_arg)
{
    boost::uuids::detail::sha1 sha1;
    sha1.process_bytes(p_arg.data(), p_arg.size());
    unsigned hash[5] = {0};
    sha1.get_digest(hash);

    // Back to string
    char buf[41] = {0};

    for (int i = 0; i < 5; i++)
    {
        std::sprintf(buf + (i << 3), "%08x", hash[i]);
    }

    return std::string(buf);
}

这篇关于如何在C ++中可移植地计算sha1哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆