gpt4 book ai didi

c++ - 使用 crypto++ 在 C++ 中散列包含 NUL 字符的字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:41:26 24 4
gpt4 key购买 nike

在 C++(准确地说是 C++11)中,我想获取包含 NUL 字符(所有八位都设置为 0 的 ASCII 字符)的字符串的 HMAC SHA512 哈希值。

使用 crypto++,到目前为止我的方法如下:

std::string message("My\0Message",2+1+7);

std::string key_base64 = "MYSECRETKEY";
std::string key;
StringSource ss(key_base64, true, new Base64Decoder(new StringSink(key)));

std::string mac, encoded;

HMAC< SHA512 > hmac((byte*)key.c_str(), key.length());

StringSource(message,
true,
new HashFilter(hmac, new StringSink(mac))
); // StringSource

encoded.clear();
StringSource(mac,
true,
new Base64Encoder(new StringSink(encoded), false) // Base64Encoder. Pass argument 'false' to prevent insertion of line breaks
); // StringSource

std::cout << "Hashed message (Base64): " << encoded << std::endl;

当上面的 message 字符串中包含 NUL 字符时,这将无法正常工作。

我得到的散列(变量 mac)的 base64 编码版本是

bXmQCkzhzq3J81vInF6IRtxXyd+mN8TRh8e3qHThJ+/RYVcgRkFZ9iStKnNaVsGgco/nisUeRpT3m388UR/BMg==

而不是预期的

hUk4PX3mnqs943JnMR+ptW6f8+enIUGBd4x7sUA+Ug2squOFVF6ZdiCewSBDlGAwNuWf+9Uh0AqUkQV1vMNHxg==

编辑

可以从 Bash 命令行获得预期的输出,如下所示:

hex_encoded_secret=$(echo -n "MYSECRETKEY" | base64 --decode | xxd -p | tr '\n' ' ' | tr -d '[:space:]')
echo -ne "My\0Message" | openssl dgst -sha512 -mac HMAC -macopt hexkey:"${hex_encoded_secret}" -binary | base64 | tr -d '\n'

这会生成上面给出的预期输出。

最佳答案

This doesn't work properly when a NUL character is included as in the message string above.

您使用的构造函数应该没问题,因为机器使用 std::string::size(),而不是 std::string::c_str() 来确定长度。我怀疑还有其他问题不太正确,例如字符编码问题。

您正在使用 StringSourcestd::string 构造函数。 StringSource 的第二个构造函数采用二进制字符串。在您的生产代码中使用它可能会更好:

StringSource(reinterpret_cast<const byte*>(&message[0]),
message.size(),
true,
new HashFilter(hmac, new StringSink(mac))
); // StringSource

另见 StringSource在 Crypto++ wiki 上。

关于c++ - 使用 crypto++ 在 C++ 中散列包含 NUL 字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49477520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com