我的代码中的HMAC-SHA512错误

HMAC-SHA512 bug in my code

本文关键字:HMAC-SHA512 错误 代码 我的      更新时间:2023-10-16

我将非常感激,如果你能帮助我这个c++实现的HMAC-SHA512代码,我似乎找不到为什么它给出了一个不同的哈希比在线转换器。(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;
}

原来BLOCKSIZE是错误的

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

所以只需将代码改为

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

你得到了正确的结果

感谢您的快速响应,问题出在哈希函数上(某种程度上)。sha512输出在返回之前被转换为十六进制,因此"sha512(i_key_pad +消息)"没有回答我所期望的。(块大小也是1024)