首页 > 解决方案 > 生成 blake2b 哈希时崩溃

问题描述

我正在尝试使用 Botan 作为后端编写一个哈希函数,即:

std::string hex_hash(std::string &in, const std::string &HASH)
{
std::unique_ptr<Botan::HashFunction> hash(Botan::HashFunction::create(HASH));

return Botan::hex_encode(hash->process(in));
}

HASHstd::string请求的哈希的名称。即"SHA-512"对于 SHA512 和"BLAKE2b"BLAKE2b

botan 支持的任何其他哈希都会被处理和输出,但 BLAKE2b 不会并抛出异常:

Exception thrown at 0x00007FF661382C5A in test.exe: 0xC0000005: Access violation reading location 0x0000000000000000.

然后崩溃。

我确实在植物手册(https://botan.randombit.net/manual/hash.html)中注意到

布莱克2b

如果定义了 BOTAN_HAS_BLAKE2B,则可用。

最近设计的哈希函数。在 64 位处理器上非常快。可以输出 1 到 64 字节之间任意长度的散列,这是通过将值传递给具有所需长度的构造函数来指定的。

有没有可能没有默认设置?我将如何设置它?有没有可能我的名字错了?

标签: c++hashbotan

解决方案


问题可能是名称的大写。我正在使用 Botan 2.9.0 和“Blake2b”工作,而“BLAKE2b”崩溃。Botan 的 master 分支也接受“BLAKE2b”,但这是最近才添加的。默认输出长度设置为 512 位,您可以通过传递例如“Blake2b(256)”或直接调用 Blake2b 构造函数(如在链接提交中)来调整它。

小型工作示例(main.cpp):


#include <iostream>
#include <memory>
#include <string>

#include "botan/hash.h"
#include "botan/hex.h"

std::string hex_hash(const std::string& in, const std::string& HASH) {
    std::unique_ptr<Botan::HashFunction> hash(Botan::HashFunction::create(HASH));
    return Botan::hex_encode(hash->process(in));
}

int main(int argc, char** argv) {
    std::cout << "Blake2b " << hex_hash("abc", "Blake2b") << std::endl;
    std::cout << "Blake2b(256) " << hex_hash("abc", "Blake2b(256)") << std::endl;
    return 0;
}
$ g++ `pkgconf --cflags --libs botan-2` main.cpp && ./a.out 
Blake2b BA80A53F981C4D0D6A2797B69F12F6E94C212F14685AC4B74B12BB6FDBFFA2D17D87C5392AAB792DC252D5DE4533CC9518D38AA8DBF1925AB92386EDD4009923
Blake2b(256) BDDD813C634239723171EF3FEE98579B94964E3BB1CB3E427262C8C068D52319

如果这对您不起作用,还请确保您的 Botan 编译时支持 Blake2b,例如

$ grep BLAKE /usr/include/botan-2/botan/build.h 
#define BOTAN_HAS_BLAKE2B 20130131

推荐阅读