簡體   English   中英

我在PHP中實現HMAC有什么問題?

[英]What's wrong with my implementation of HMAC in PHP?

我正在嘗試在PHP中實現通用HMAC函數。 我正在關注RFCWikipedia頁面 ,但是無法獲取與示例輸出匹配的函數。 我究竟做錯了什么?

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";

您使用整數而不是要重復的字符串調用string_repeat() 因此,適用於整數到字符串的轉換。 這意味着當前您得到的內容類似於0x36 -> '54' -> '54545454...5454''54'重復了64次)等等。 使用chr(0x36)獲取實際字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM