c++ - 使用 OpenSSL 1.1 的 SHA256 HMAC 未编译

标签 c++ openssl debian sha256 hmac

下面的代码使用 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 的向后兼容性的方式修复它?

最佳答案

修复错误,请阅读:Upgrade To OpenSSL 1.1.0 .基本上,您需要按如下方式创建一个新的 HMAC_CTX:

HMAC_CTX *h = HMAC_CTX_new();
HMAC_Init_ex(h, key, keylen, EVP_sha256(), NULL);
...
HMAC_CTX_free(h);

为了向后兼容,可以考虑使用宏来控制要编译的代码块。

关于c++ - 使用 OpenSSL 1.1 的 SHA256 HMAC 未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44771701/

相关文章:

c++ - 在其他 OpenGL 前面渲染的对象

c++ - 表达式周围的括号和大括号基本上做同样的事情吗?

python - 如何在 Python 中使用 M2Crypto 重新创建以下签名 cmd 行 OpenSSL 调用?

c - 从 ASN.1 格式的证书获取 DN

heroku - SSL 证书验证结果 : unable to get local issuer certificate (20)

r - 在 R 升级期间用户安装了 R 包的 Ubuntu/Debian 上会发生什么

c++ - - 9'223' 37 2'036' 85 4'775' 808LL 未签名

C++ Debian SDL 段错误

django - 在公共(public)网站准备好启动之前限制对其的访问?

c++ - 建议为 C++ 选择线性代数库