Python 和 PHP 中的 HMAC 值不一致

HMAC value not consistent in Python and PHP

我正在尝试使用 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;

Shevron 是对的:行结尾不同。

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

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