HMAC值在Python和PHP中不一致

时间:2015-08-10 12:07:57

标签: php python hmac

我正在尝试使用HMAC来散列数据字符串但由于某些原因我的PHP和Python脚本结果不一致......我无法弄清楚原因。

技术上工作的是Python脚本,虽然我从PHP脚本获得结果,但返回的十六进制不正确。

更新 - 我注意到的一件事是,如果我使用单行数据,那么结果是相同的。当存在多行数据时,似乎会发生不匹配。

这里的Python演示脚本 https://repl.it/BBDH/2

结果:

  

f54617eadc7c037b4ed484103bb21426994110a9

import hashlib
import hmac
import base64

key = b"M0u$t4fa@1Kh-Key"

csr = """-----BEGIN NEW CERTIFICATE REQUEST-----
MIICtzCCAZ8CAQAwcjELMAkGA1UEBhMCQVUxETAPBgNVBAgMCFZpY3RvcmlhMRIw
EAYDVQQHDAlNZWxib3VybmUxDzANBgNVBAoMBk1LVEVTVDELMAkGA1UECwwCSVQx
HjAcBgNVBAMMFWRuc3Rlc3QzLnNzbHRlY2hzLmNvbTCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAM1Ik2SS1F4NgizKXCqpiliR/c285HtcLKFD6OcJO6d6
v8n+1B7R1ovUqRyoM4qsLAVVHshvsuqxbD7sLmcEfh/akee+CGLqgSNSw913IBWL
WRtBRhVTd6gvTQY4KqpEgRShnua179Cbb/cQLsFhHhog/IfD0JWwdRWLqn3rzQcI
xzAsOkTJSarAt/QPS5fq1Hk978iQ0QAxtEssaX+0Xcq7ZyJGkHRyW3cBoynSQAYz
RNGBFTFB+z/qiAkKWwRs61cnKub9Grz6Adw931zuYICW0EaWdBGdc15cUkvI6RF4
xqhzmHBTZLQZDcP9vYrE/biVvX2GVNKpO1hd0i7iOTcCAwEAAaAAMA0GCSqGSIb3
DQEBCwUAA4IBAQBPmct14B0f7HkMar8Ogf1wgo7jXyFytW7tfj3exTsyBC/5ShGv
1Xx//H8I5ecb5N6EflyXmaFiWM4ybQduhVyKzNxlU8i5ug/msdpxQhj3rZ7WO6Xb
O8b5oj5e/8V1RmmsjC9dDFA/A8/JgAbrOn2CtCJrgRtl1LFBtaFRonfaRbuzcVSE
e1qdKoPY2UNK7cd3Hv/pkkorUJd89YREFZatyvU/b89fjNaPzjvtljxGadeIX5WO
7sQwMyHCSknWZPY4BYaiMf6jZ8TjXOCyIHQ3bdiDSiJlUEXvgz2yhF6Uue6aTvhR
Q85mPbtxXP+JXiZgSuT0Q6n7qN1b1mbZJgwk
-----END NEW CERTIFICATE REQUEST-----""".encode('utf-8')

hashed = hmac.new(key, csr, digestmod=hashlib.sha1).hexdigest()
print("HMAC (hex) =", hashed)

这里的PHP演示脚本 https://repl.it/BBDF/2

结果:

  

e978d0d10b814e486592ed608b5f16d095a9affa

$key = 'M0u$t4fa@1Kh-Key';
$data = '-----BEGIN NEW CERTIFICATE REQUEST-----
MIICtzCCAZ8CAQAwcjELMAkGA1UEBhMCQVUxETAPBgNVBAgMCFZpY3RvcmlhMRIw
EAYDVQQHDAlNZWxib3VybmUxDzANBgNVBAoMBk1LVEVTVDELMAkGA1UECwwCSVQx
HjAcBgNVBAMMFWRuc3Rlc3QzLnNzbHRlY2hzLmNvbTCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAM1Ik2SS1F4NgizKXCqpiliR/c285HtcLKFD6OcJO6d6
v8n+1B7R1ovUqRyoM4qsLAVVHshvsuqxbD7sLmcEfh/akee+CGLqgSNSw913IBWL
WRtBRhVTd6gvTQY4KqpEgRShnua179Cbb/cQLsFhHhog/IfD0JWwdRWLqn3rzQcI
xzAsOkTJSarAt/QPS5fq1Hk978iQ0QAxtEssaX+0Xcq7ZyJGkHRyW3cBoynSQAYz
RNGBFTFB+z/qiAkKWwRs61cnKub9Grz6Adw931zuYICW0EaWdBGdc15cUkvI6RF4
xqhzmHBTZLQZDcP9vYrE/biVvX2GVNKpO1hd0i7iOTcCAwEAAaAAMA0GCSqGSIb3
DQEBCwUAA4IBAQBPmct14B0f7HkMar8Ogf1wgo7jXyFytW7tfj3exTsyBC/5ShGv
1Xx//H8I5ecb5N6EflyXmaFiWM4ybQduhVyKzNxlU8i5ug/msdpxQhj3rZ7WO6Xb
O8b5oj5e/8V1RmmsjC9dDFA/A8/JgAbrOn2CtCJrgRtl1LFBtaFRonfaRbuzcVSE
e1qdKoPY2UNK7cd3Hv/pkkorUJd89YREFZatyvU/b89fjNaPzjvtljxGadeIX5WO
7sQwMyHCSknWZPY4BYaiMf6jZ8TjXOCyIHQ3bdiDSiJlUEXvgz2yhF6Uue6aTvhR
Q85mPbtxXP+JXiZgSuT0Q6n7qN1b1mbZJgwk
-----END NEW CERTIFICATE REQUEST-----';
$hmac = hash_hmac('sha1', $data, $key);
echo "HMAC (hex) = ".$hmac;

1 个答案:

答案 0 :(得分:2)

Shevron是对的:行结尾是不同的。

在计算哈希值之前添加:$data = str_replace("\r\n", "\n", $data);

这是更正后的rept.it文件。 https://repl.it/BBDF/4