自编HMAC功能,无法正常工作

时间:2017-10-06 14:16:46

标签: c++ hmac

我编写了以下函数来生成引用https://tools.ietf.org/html/rfc2104的HMAC-SHA1,但是,我生成的值似乎与https://tools.ietf.org/html/rfc2202上给出的值以及我在{{}}上测试的值不同{3}}。

例如,该函数应该为文本生成de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"快速的棕色狐狸跳过懒狗"使用键"键",但它会生成d3c446dbd70f5db3693f63f96a5931d49eaa5bab

有人能指出我的错误吗?

功能:

const int block_size = 64;
const int hash_output_size = 20;
const int ipadVal = 0x36;
const int opadVal = 0x5C;
std::string HMAC::getHMAC(const std::string &text)
{
// check if key length is block_size
// else, append 0x00 till the length of new key is block_size
int key_length = key.length();
std::string newkey = key;
if (key_length < block_size)
{
    int appended_zeros = block_size - key_length;
    // create new string with appended_zeros number of zeros
    std::string zeros = std::string(appended_zeros, '0');
    newkey = key + zeros;
}
if (key_length > block_size)
{
    SHA1 sha1;
    newkey = sha1(key);
}

// calculate hash of newkey XOR ipad and newkey XOR opad
std::string keyXipad = newkey;
std::string keyXopad = newkey;
for (int i = 0; i < 64; i++)
{
    keyXipad[i] ^= ipadVal;
    keyXopad[i] ^= opadVal;
}

// get first hash, hash of keyXipad+text
std::string inner_hash = getSHA1(keyXipad + text);

// get outer hash, hash of keyXopad+inner_hash
std::string outer_hash = getSHA1(keyXopad + inner_hash);

// return outer_hash
return outer_hash;
}

编辑:在行

std::string zeros = std::string(appended_zeros, '0');

&#39; 0&#39;应该是0而不是:int而不是char。感谢@Igor Tandetnik。

1 个答案:

答案 0 :(得分:0)

好的。看看周围有点引导我HMAC produces wrong results。事实证明,我使用hex作为ascii也犯了同样的错误。

我使用了一个函数将inner_hash从hex转换为ascii,然后一切都变得完美。

该功能的最终版本:

std::string HMAC::getHMAC(const std::string &text)
{
// check if key length is block_size
// else, append 0x00 till the length of new key is block_size
int key_length = key.length();
std::string newkey = key;
if (key_length < block_size)
{
    int appended_zeros = block_size - key_length;
    // create new string with appended_zeros number of zeros
    std::cout << "\nAppending " << appended_zeros << " 0s to key";
    std::string zeros = std::string(appended_zeros, 0);
    newkey = key + zeros;
}
if (key_length > block_size)
{
    SHA1 sha1;
    newkey = sha1(key);
}

// calculate hash of newkey XOR ipad and newkey XOR opad
std::string keyXipad = newkey;
std::string keyXopad = newkey;
for (int i = 0; i < 64; i++)
{
    keyXipad[i] ^= ipadVal;
    keyXopad[i] ^= opadVal;
}

// get first hash, hash of keyXipad+text
std::string toInnerHash = keyXipad + text;
std::string inner_hash = getHash(toInnerHash);

// get outer hash, hash of keyXopad+inner_hash
std::string toOuterHash = keyXopad + hex_to_string(inner_hash);
std::string outer_hash = getHash(toOuterHash);

// return outer_hash
return outer_hash;
}

hex_to_string函数取自https://stackoverflow.com/a/16125797/3818617