我正在寻找一些函数或一种使用密钥在 C++ 中返回 HMAC SHA256 哈希的方法。我看过 Crypto++ 和 OpenSSL 的文档,但它不接受用于计算的额外密钥参数。有人可以通过提供一些信息、代码片段或链接来帮助我。
为了保持一致性,以下是使用 OpenSSL 生成 SHA256-HMAC 的函数示例
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <string>
#include <string_view>
#include <array>
std::string CalcHmacSHA256(std::string_view decodedKey, std::string_view msg)
{
std::array<unsigned char, EVP_MAX_MD_SIZE> hash;
unsigned int hashLen;
HMAC(
EVP_sha256(),
decodedKey.data(),
static_cast<int>(decodedKey.size()),
reinterpret_cast<unsigned char const*>(msg.data()),
static_cast<int>(msg.size()),
hash.data(),
&hashLen
);
return std::string{reinterpret_cast<char const*>(hash.data()), hashLen};
}
Run Code Online (Sandbox Code Playgroud)
根据记录,我更喜欢 Crypto++,因为 Crypto++ 生成的二进制文件更小。缺点是 Crypto++ 没有 CMake 模块。
您可以使用POCO 库
示例代码:
class SHA256Engine : public Poco::Crypto::DigestEngine
{
public:
enum
{
BLOCK_SIZE = 64,
DIGEST_SIZE = 32
};
SHA256Engine()
: DigestEngine("SHA256")
{
}
};
Poco::HMACEngine<SHA256Engine> hmac{secretKey};
hmac.update(string);
std::cout << "HMACE hex:" << Poco::DigestEngine::digestToHex(hmac.digest()) << std::endl;// lookout difest() calls reset ;)
Run Code Online (Sandbox Code Playgroud)
mkdir build_poco/
cd build_poco/ && cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./install ../poco/
Run Code Online (Sandbox Code Playgroud)
CMAKE_MINIMUM_REQUIRED(VERSION 3.8)
PROJECT(SamplePoco)
SET(CMAKE_CXX_STANDARD 14)
SET(SOURCE_FILES
src/main.cpp
)
SET(_IMPORT_PREFIX lib/build_poco/install)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoFoundationTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoNetTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoJSONTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoXMLTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoCryptoTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoUtilTargets.cmake)
INCLUDE(lib/build_poco/install/lib/cmake/Poco/PocoNetSSLTargets.cmake)
ADD_EXECUTABLE(SamplePoco ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(SamplePoco
Poco::Foundation
Poco::Crypto
Poco::Util
Poco::JSON
Poco::NetSSL
)
TARGET_INCLUDE_DIRECTORIES(SamplePoco PUBLIC src/)
Run Code Online (Sandbox Code Playgroud)
此处使用的示例实现:https : //github.com/gelldur/abucoins-api-cpp
小智 3
HMAC的 OpenSSL 文档明确规定了“密钥”的要求作为上下文初始化的一部分。
int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int key_len,
const EVP_MD *md, ENGINE *impl);
Run Code Online (Sandbox Code Playgroud)
HMAC()使用哈希函数evp_md和key_len字节长的密钥key计算d处n个字节的消息认证码。