【问题标题】:C# HMACSHA1 vs PHP hash_hmacC# HMACSHA1 与 PHP hash_hmac
【发布时间】:2020-06-09 15:02:48
【问题描述】:

我正在尝试使用 PHP 连接到 API 以获取访问令牌,并且唯一的哈希示例代码是用 C# 编写的。这是 C# 版本:

private static string GetHMACSignature(string privatekey, string message)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(privatekey);
            Console.WriteLine("Key: "+ToReadableByteArray(keyByte));

            System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(keyByte);
            byte[] messageBytes = encoding.GetBytes(message);
            Console.WriteLine("Message: "+ToReadableByteArray(messageBytes));
            byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
            Console.WriteLine("Hash: "+ToReadableByteArray(hashmessage));
            return Convert.ToBase64String(hashmessage);
        }

使用“a1”的私钥和“b1”的消息,您会得到以下信息:

Key: 97, 49
Message: 98, 49
Hash: 219, 205, 149, 90, 235, 40, 133, 252, 91, 27, 240, 61, 201, 173, 220, 76, 73, 248, 92, 212
282VWusohfxbG/A9ya3cTEn4XNQ=

当我尝试在 PHP 中运行等效项时,我得到相同的字节,但哈希值不同:

$key = 'a1';
$message = 'b1';
$hmac = hash_hmac('sha1', $key, $message, true);
$hmac_base64 = base64_encode($hmac);

echo 'KEY BYTES: '.implode(',',$this->getByteArray($key)).'<br>';
echo 'MESSAGE BYTES: '.implode(',',$this->getByteArray($message)).'<br>';
echo 'HMAC BYTES: '.implode(',',$this->getByteArray($hmac)).'<br>';
echo 'HMAC: '.$hmac_base64;

function getByteArray($text) {
     $secretBytes = array();
        for($i = 0; $i < strlen($text); $i++)
         {
           $secretBytes[] = ord($text[$i]);
         }

     return $secretBytes;
}

结果:

KEY BYTES: 97,49
MESSAGE BYTES: 98,49
HMAC BYTES: 3,162,147,8,198,26,126,189,195,122,228,215,10,18,187,216,22,151,202,237
HMAC: A6KTCMYafr3DeuTXChK72BaXyu0=

我做错了什么?我在这里发现的很多问题都说在 PHP 中将 hash_hmac 的二进制输出设置为 true,我已经这样做了。最初我的消息中有返回 (\r) 和换行符 (\n),所以我认为这可能是 ASCII 转换问题,但使用 a1b1 运行它> 作为键和消息仍然不会导致匹配的哈希,即使字节数组匹配。任何帮助表示赞赏,在此先感谢您!

【问题讨论】:

    标签: c# php sha1 hmacsha1


    【解决方案1】:

    我对@9​​87654322@ 了解不多,但根据documentation on hash_hmac 看来,您可能会将$key$data 参数颠倒过来。

    来自文档:

    hash_hmac ( 字符串 $algo , 字符串 $data , 字符串 $key [, bool $raw_output = FALSE ] ) : 字符串

    因此,您似乎将$message 作为键传递,$key 作为消息传递。

    【讨论】:

      【解决方案2】:

      就是这样,我把钥匙和信息颠倒了。谢谢!

      【讨论】:

        猜你喜欢
        • 2020-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多