【发布时间】:2017-11-30 00:01:23
【问题描述】:
以下代码使用 HMAC SHA256 生成签名哈希。此代码在 Debian Jessie 和 Ubuntu 16.04(OpenSSL 1.0.2g 2016 年 3 月 1 日)上编译并运行良好。
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string HMAC256(string data, string key)
{
stringstream ss;
HMAC_CTX ctx;
unsigned int len;
unsigned char out[EVP_MAX_MD_SIZE];
HMAC_Init(&ctx, key.c_str(), key.length(), EVP_sha256());
HMAC_Update(&ctx, (unsigned char*)data.c_str(), data.length());
HMAC_Final(&ctx, out, &len);
HMAC_cleanup(&ctx);
for (unsigned int i = 0; i < len; i++)
{
ss << setw(2) << setfill('0') << hex << static_cast<int> (out[i]);
}
return ss.str();
}
int main()
{
cout << HMAC256("AAAA","BBBB") << endl;
return 0;
}
但是....
在 Debian Stretch 上编译时出现以下错误:
hmac256.cpp: In function ‘std::__cxx11::string HMAC256(std::__cxx11::string, std::__cxx11::string)’:
hmac256.cpp:14:18: error: aggregate ‘HMAC_CTX ctx’ has incomplete type and cannot be defined
HMAC_CTX ctx;
^~~
hmac256.cpp:18:9: warning: ‘int HMAC_Init(HMAC_CTX*, const void*, int, const EVP_MD*)’ is deprecated [-Wdeprecated-declarations]
HMAC_Init(&ctx, key.c_str(), key.length(), EVP_sha256());
^~~~~~~~~
In file included from /usr/include/openssl/hmac.h:13:0,
from hmac256.cpp:2:
/usr/include/openssl/hmac.h:28:1: note: declared here
DEPRECATEDIN_1_1_0(__owur int HMAC_Init(HMAC_CTX *ctx, const void *key, int len,
^
这与新的 OpenSSL 版本(OpenSSL 1.1.0f 2017 年 5 月 25 日)有关。
问题
为什么我会遇到 OpenSSL 1.1 的问题,以及如何以保持与 OpenSSL 1.0 向后兼容性的方式解决它?
【问题讨论】:
-
请参阅 OpenSSL wiki 上的 OpenSSL 1.1.0 Changes(特别是,请参阅兼容层内容)。另请参阅 Stack Overflow 上的 Error: incomplete type when using HMAC_CTX in C++ project、Error: “invalid use of incomplete type ‘RSA {aka struct rsa_st}” in OpenSSL 1.1.0、Error “incomplete type MD5_CONTEXT” with MariaDB 10.2 and Openssl 1.1.0e 等。
-
您应该只使用 EVP 接口。它们在 OpenSSL 1.0.2 和 OpenSSL 1.1.0 中似乎是稳定的。为此,请参阅 OpenSSL wiki 上的 EVP Signing and Verifying。您可能还对EVP Symmetric Encryption and Decryption | C++ Programs 感兴趣。它在使用 C++ 时提供了一些技巧。
标签: c++ openssl debian sha256 hmac