MD5 HMAC With OpenSSL

假如想象 提交于 2019-12-01 04:24:29

问题


I was trying to generate MD5 HMAC with OpenSSL & most of the code is borrowed. The hmac being generate is incorrect:

#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <syslog.h>
#include <string.h>

#include <openssl/engine.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() 
{
  unsigned char* key = (unsigned char*) "2012121220121212201212122012121220121212201212122012121220121212";
  unsigned char* data = (unsigned char*) "johndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoe";
  unsigned char* expected = (unsigned char*) "abcd1d87dca34f334786307d0da4fcbd";
  unsigned char* result;
  // unsigned int result_len = 16;
  unsigned int result_len = 16;
  int i;
  static char res_hexstring[32];

  // result = HMAC(EVP_sha256(), key, 4, data, 28, NULL, NULL);
  result = HMAC(EVP_md5(), key, 32, data, 28, NULL, NULL);
  for (i = 0; i < result_len; i++) {
    sprintf(&(res_hexstring[i * 2]), "%02x", result[i]);
  }

  if (strcmp((char*) res_hexstring, (char*) expected) == 0) {
    printf("Test ok, result length %d\n", result_len);
  } else {
    printf("Got %s instead of %s\n", res_hexstring, expected);
  }
}

The hash being produced is incorrect. I would appreciate some feedback or someone pointing me in the right direction.


回答1:


The third and fifth parameters to HMAC are just wrong. You have to pass the length of the key and the length of data. In your example, this is respectively 64 and 84, not 32 and 28.

So :

-    result = HMAC(EVP_md5(), key, 32, data, 28, NULL, NULL);                                                                                                                                                                         
+    result = HMAC(EVP_md5(), key, 64, data, 84, NULL, NULL); 

With this modification, it seems to be working fine.




回答2:


You can make the all-in-one OpenSSL HMAC command tidier, if you write:

result = HMAC(EVP_md5(), key, sizeof(key)-1, data, sizeof(data)-1, NULL, NULL);

Because key and data are initialized with string literals, the last char of both is \0. This termination character should not be hashed. We skip this character by specifing the size of the array minus the last char.

You can get other Test Vectors for HMAC-MD5 from https://tools.ietf.org/html/rfc2202.




回答3:


Use

result = HMAC(EVP_md5(), key, strlen(key), data, strlen(data), NULL, NULL);

Instead of

result = HMAC(EVP_md5(), key, 32, data, 28, NULL, NULL);

It generally work for any data & key



来源:https://stackoverflow.com/questions/13555962/md5-hmac-with-openssl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!