2012-11-25 153 views
4

我試圖生成MD5 HMAC使用OpenSSL &大部分代碼是借來的。正在生成的hmac不正確:MD5 HMAC使用OpenSSL

#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); 
    } 
} 

生成的散列不正確。我會感謝一些反饋或有人指出我在正確的方向。

回答

4

HMAC的第三個和第五個參數是錯誤的。您必須通過密鑰長度和數據長度。在示例中,這是分別爲64和84,而不是32和28

所以:

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

有了這個修改,它似乎是正常工作。

0

可以使所有功能於一身的OpenSSL HMAC命令整潔,如果你寫:

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

您可以從https://tools.ietf.org/html/rfc2202得到HMAC-MD5等測試向量。