我的代码中的HMAC-SHA512错误

时间:2014-07-15 07:17:56

标签: c++ hmac

我非常感谢,如果你能帮助我使用HMAC-SHA512代码的c ++实现,我似乎无法找到它为什么提供与在线转换器不同的哈希值。 (SHA512工作得很好。)

代码(基于维基百科):

#include <iostream>
#include "sha512.h"

using namespace std;

const unsigned int BLOCKSIZE = (512/8); // 64 byte

int main(int argc, char *argv[])
{
    if(argc!=3)return 0;
    string key = argv[1];
    string message = argv[2];

    if(key.length() > BLOCKSIZE){
        key = sha512(key);
    }
    while(key.length() < BLOCKSIZE){
        key = key + (char)0x00;
    }

    string o_key_pad = key;
    for(unsigned int i = 0; i < BLOCKSIZE; i++){
        o_key_pad[i] = key[i] ^ (char)0x5c;
    }

    string i_key_pad = key;
    for(unsigned int i = 0; i < BLOCKSIZE; i++){
        i_key_pad[i] = key[i] ^ (char)0x36;
    }

    string output = sha512(o_key_pad + sha512(i_key_pad + message));

    cout<<"hmac-sha512: \n"<<output<<endl;

    return 0;
}

2 个答案:

答案 0 :(得分:2)

事实证明BLOCKSIZE不正确。

根据http://en.wikipedia.org/wiki/SHA-2,sha-512的块大小为1024位,即128字节。

只需将代码更改为

即可
const unsigned int BLOCKSIZE = (1024/8); // 128 byte

你得到了正确的结果。

答案 1 :(得分:0)

感谢您的快速回复,问题在于哈希函数(排序)。 sha512输出在返回之前转换为十六进制,因此&#34; sha512(i_ke​​y_pad + message)&#34;没有回答我的期待。 (而且块大小也是1024)

相关问题