亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# HMACSHA1 與 PHP hash_hmac

C# HMACSHA1 與 PHP hash_hmac

PHP
開滿天機 2023-05-12 16:09:55
我正在嘗試連接到 API 以使用 PHP 獲取訪問令牌,并且唯一的散列示例代碼是用 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, 49Message: 98, 49Hash: 219, 205, 149, 90, 235, 40, 133, 252, 91, 27, 240, 61, 201, 173, 220, 76, 73, 248, 92, 212282VWusohfxbG/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,49MESSAGE BYTES: 98,49HMAC BYTES: 3,162,147,8,198,26,126,189,195,122,228,215,10,18,187,216,22,151,202,237HMAC: A6KTCMYafr3DeuTXChK72BaXyu0=我究竟做錯了什么?我在這里發現的很多問題都說要在 PHP 中將 hash_hmac 的二進制輸出設置為 true,我已經做到了。最初我的消息中有返回 (\r) 和換行符 (\n),所以我認為這可能是 ASCII 轉換問題,但是以 a1 和 b1 作為鍵和消息運行它仍然不會導致匹配的哈希值,即使字節數組匹配。感謝您的幫助,在此先感謝您!
查看完整描述

2 回答

?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

我不太了解PHP,但根據它的文檔,hash_hmac您似乎可能將$key$data參數顛倒了。

從文檔中:

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

因此,看起來您將$message作為鍵和$key消息傳遞。


查看完整回答
反對 回復 2023-05-12
?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

就是這樣,我把密鑰和消息顛倒了。謝謝你!



查看完整回答
反對 回復 2023-05-12
  • 2 回答
  • 0 關注
  • 248 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號