我正在尝试设置 HMAC-SHA-256 散列的基本测试,但我遇到了引擎设置问题。理想情况下,我只想设置 HMAC-SHA 算法,但到目前为止,我什至还没有得到加载所有算法工作的一般情况。目前,我在尝试设置默认摘要的行上遇到了段错误。
另外,我经常使用 Java,因此请随时指出代码中的任何错误。
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
unsigned char* data = (unsigned char*) "4869205468657265";
unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
unsigned char* result;
HMAC_CTX* ctx;
ENGINE* e;
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
ENGINE_set_default_digests(e);
HMAC_CTX_init(ctx);
HMAC_Init_ex(ctx, key, 40, EVP_sha256(), e);
result = HMAC(NULL, NULL, 40, data, 16, NULL, NULL);
HMAC_CTX_cleanup(ctx);
ENGINE_finish(e);
ENGINE_free(e);
if (strcmp((char*) result, (char*) expected) == 0) {
printf("Test ok\n");
} else {
printf("Got %s instead of %s\n", result, expected);
}
}
编辑:该程序现在已经发展到以下,但我仍然在 segfaulting HMAC_Init_ex
:
unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
unsigned char* data = (unsigned char*) "4869205468657265";
unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
unsigned char* result;
unsigned int result_len = 64;
HMAC_CTX ctx;
ENGINE* e;
result = (unsigned char*) malloc(sizeof(char) * result_len);
e = (ENGINE*) ENGINE_new();
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
ENGINE_set_default_digests(e);
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key, 16, EVP_sha256(), e);
HMAC_Update(&ctx, data, 40);
HMAC_Final(&ctx, result, &result_len);
HMAC_CTX_cleanup(&ctx);
ENGINE_finish(e);
ENGINE_free(e);