I'm trying to set up a basic test of HMAC-SHA-256 hashing but I'm having problems with the engine setup. Ideally I would like to set up only the HMAC-SHA-algorithm but so far I haven't even gotten the general case where load all the algorithms to work. Currently I'm getting segfaults on the row where I try to set the default digests.
Also, I'm regularly a Java guy, so don't hesitate to point out any mistakes in the code.
#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
");
} else {
printf("Got %s instead of %s
", result, expected);
}
}
EDIT: The program has now evolved to the following, but I'm still segfaulting at 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);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…