OpenSSL中的HMAC-SHA256实现

时间:2019-01-28 09:17:32

标签: c++ openssl

我已经使用openssl库通过HMAC_CTX实现HMAC-SHA256。 实际输出与预期输出不同。我已经尝试过此代码

int hmac_sha256(char *key, const unsigned char *string, int mlen, char 
outputBuffer[65])
{
unsigned int len = 0;
//unsigned char hash[EVP_MAX_MD_SIZE];
unsigned char hash[65];

unsigned char *ptr = NULL;
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha256(), NULL);
HMAC_Update(&ctx, string, mlen);
HMAC_Final(&ctx, hash, &len);
 for (int i = 0; i < 65; i++)
{
    sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
HMAC_CTX_cleanup(&ctx);
return 1;}

在主代码中:

字符签名[65];

retVal = hmac_sha256(key,(const unsigned char *)tempMessage,strlen(tempMessage),签名);

我尝试了另一个

int hmac(unsigned char *key, unsigned int key_len, unsigned char *data, 
unsigned int data_len, char outputBuffer[64], unsigned int *out_len)

{

#define BLOCK_SIZE 64

unsigned int i, nkey, o_len;
char i_pad[BLOCK_SIZE], o_pad[BLOCK_SIZE];

/* Key init */

if (key_len > BLOCK_SIZE)
    key = hash(key, key_len, &nkey);
else if (key_len < BLOCK_SIZE) 
{
    // zero pad to the right
    char *n_key =(char *) malloc(BLOCK_SIZE);
    memset(n_key, '\0', BLOCK_SIZE);
    memcpy(n_key, key, key_len);
    key =(unsigned char *)n_key;
}

for (i = 0; i<BLOCK_SIZE; i++) 
{
    o_pad[i] = key[i] ^ 0x5c;
    i_pad[i] = key[i] ^ 0x36;
}

unsigned char *stg1 =(unsigned char*) malloc(BLOCK_SIZE + data_len);
memcpy(stg1, i_pad, BLOCK_SIZE);
memcpy(stg1 + BLOCK_SIZE, data, data_len);


stg1 = hash(stg1, BLOCK_SIZE + data_len, &o_len);

unsigned char *stg2 =(unsigned char*) malloc(BLOCK_SIZE + o_len);
memcpy(stg2, o_pad, BLOCK_SIZE);
memcpy(stg2 + BLOCK_SIZE, stg1, o_len);


stg2 = hash(stg2, BLOCK_SIZE * 2 + data_len, &o_len);

/*EVP_MD_CTX ctx;
EVP_MD_CTX_init(&ctx);
EVP_DigestInit_ex(&ctx, EVP_sha256(), NULL);
EVP_DigestUpdate(&ctx, o_pad, BLOCK_SIZE);
EVP_DigestUpdate(&ctx, stg1, o_len);
EVP_DigestFinal_ex(&ctx, stg2, &o_len);
 EVP_MD_CTX_cleanup(&ctx);*/

for (int i = 0; i < 32; i++)
{
 sprintf(outputBuffer + (i * 2), "%02x", stg2[i]);
}

  return 1;
 }

实际输出与预期输出不同。 我无法提供示例,因为它们是5000字节长的XML数据。

0 个答案:

没有答案