使用OpenSSL 1.1的SHA256 HMAC无法编译 [英] SHA256 HMAC using OpenSSL 1.1 not compiling
问题描述
下面的代码使用HMAC SHA256生成带符号的哈希。这段代码可以在Debian Jessie和Ubuntu 16.04(OpenSSL 1.0.2g,2016年3月1日)上编译并正常工作。
The code below generates a signed hash using HMAC SHA256. This code compiles and works fine on Debian Jessie and Ubuntu 16.04 (OpenSSL 1.0.2g 1 Mar 2016).
#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上编译时,出现以下错误:
When compiling it on Debian Stretch I get the following error:
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日)有关。
And this has to do with the new OpenSSL version (OpenSSL 1.1.0f 25 May 2017).
问题
为什么我遇到了OpenSSL 1.1问题,以及如何解决该问题保持与OpenSSL 1.0向后兼容性的方法?
Why am I experiencing the problem with OpenSSL 1.1, and how to fix it in a way that maintains backward compatibility with OpenSSL 1.0?
推荐答案
要解决该错误,请阅读:升级到OpenSSL 1.1.0 。基本上,您需要创建新的HMAC_CTX,如下所示:
For fixing the error, please read: Upgrade To OpenSSL 1.1.0. Basically, you need to create a new HMAC_CTX as follows:
HMAC_CTX *h = HMAC_CTX_new();
HMAC_Init_ex(h, key, keylen, EVP_sha256(), NULL);
...
HMAC_CTX_free(h);
为了向后兼容,您可以考虑使用宏来控制代码块的编译。
For backward compatibility, you can consider using macros to control the code block to compile.
这篇关于使用OpenSSL 1.1的SHA256 HMAC无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!