我在PHP中实现HMAC有什么问题?

时间:2016-08-27 22:12:53

标签: php cryptography

我正在尝试在PHP中实现通用HMAC功能。我正在关注the RFCwikipedia page,但我无法使我的函数与样本输出相匹配。我做错了什么?

function myHmac(string $data, string $key, callable $algoFn, int $algoBlockSizeInBytes): string
  {
    if (strlen($key) > $algoBlockSizeInBytes)
    {
      $key = $algoFn($key); // keys longer than blocksize are shortened
    }

    if (strlen($key) < $algoBlockSizeInBytes)
    {
      $key = $key . str_repeat(0x00, $algoBlockSizeInBytes - strlen($key)); // keys shorter than blocksize are zero-padded
    }

    $outerKeyPad = str_repeat(0x5c, $algoBlockSizeInBytes) ^ $key;
    $innerKeyPad = str_repeat(0x36, $algoBlockSizeInBytes) ^ $key;

    return bin2hex($algoFn($outerKeyPad . $algoFn($innerKeyPad . $data)));
  }

$md5Fn = function ($str) { return md5($str, true); };

echo 'my output: ' . myHmac("", "", $md5Fn, 64) . "\n";
echo 'correct output: ' . hash_hmac('md5', "", "") . "\n";

1 个答案:

答案 0 :(得分:3)

使用整数调用string_repeat()而不是要重复的字符串。因此应用整数到字符串转换。这意味着目前您可以使用0x36 - &gt; '54' - &gt; '54545454...5454''54'重复64次)等等。使用chr(0x36)获取实际字节。