我正在嘗試連接到 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”的消息,您將獲得以下內(nèi)容: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=當(dāng)我嘗試在 PHP 中運行等效項時,我得到相同的字節(jié),但哈希不同:$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;}結(jié)果: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=我究竟做錯了什么?我在這里發(fā)現(xiàn)的很多問題都說要在 PHP 中將 hash_hmac 的二進制輸出設(shè)置為 true,我已經(jīng)做到了。最初我的消息中有返回 (\r) 和換行符 (\n),所以我認(rèn)為這可能是 ASCII 轉(zhuǎn)換問題,但是以 a1 和 b1 作為鍵和消息運行它仍然不會導(dǎo)致匹配的哈希值,即使字節(jié)數(shù)組匹配。感謝您的幫助,在此先感謝您!
- 2 回答
- 0 關(guān)注
- 244 瀏覽
添加回答
舉報
0/150
提交
取消