首页 > 解决方案 > Python3 中的 hash_hmac 和 bin2hex

问题描述

我得到了与使用和PHP的加密函数相关的代码。逻辑很简单。我必须消化我的然后将二进制转换为十六进制字符串hash_macbin2hexkey

这是我的PHP

$reqBody = '{
            "citizenNo":"9990601821487",
            "birthDate":"2520-02-24"
            }'; // Put JSON body into reqBody parameter
$obj = json_decode($reqBody,true);
$transformBody = json_encode($obj); // Convert JSON into string without any whitespace
$secret = "idkfaiddqd";
$hashmac = hash_hmac('sha256', $transformBody, $secret, true);
$signature = bin2hex(hash_hmac('sha256', $transformBody, $secret, true)); 

echo "X-API-key : ",$signature,"n";  

PHP28d28fd2cecc10a5d1e98a03dbec23844780d1609e7eaedba72e7c3a8e0e84e1n

我实现Python版本

        SECRET = "idkfaiddqd"
        data = {
            "citizenNo": "9990601821487",
            "birthDate": "2520-02-24",
        }
        transform_body = str(data).replace(' ', '')
        aaa = hmac.new(bytes(SECRET, 'utf-8'), transform_body.encode('utf-8'), hashlib.sha256).hexdigest()

Python2e3dff89bef78489c4f42e1e54a40b257e908aaa2d1aa46b5873acb53c51c9ac

问:
我哪里错了?

标签: phppython-3.xcryptography

解决方案


错误在transform_body字符串中。

当您查看 PHP 字符串时,您可以看到:

{"citizenNo":"9990601821487","birthDate":"2520-02-24"}

python 字符串如下所示:

{'citizenNo':'9990601821487','birthDate':'2520-02-24'}

你看得到差别吗?Python使用单引号,PHP普通引号。

要使 python 脚本与 PHP 脚本完全一样,您必须将 python 版本中的单引号替换为普通引号。

import hmac
import hashlib
SECRET = "idkfaiddqd"
data = {
  "citizenNo": "9990601821487",
  "birthDate": "2520-02-24",
}
transform_body = str(data).replace(' ', '')
transform_body = transform_body.replace('\'', '"')
aaa = hmac.new(SECRET.encode(), transform_body.encode(), hashlib.sha256).hexdigest()
print(aaa)

输出:

28d28fd2cecc10a5d1e98a03dbec23844780d1609e7eaedba72e7c3a8e0e84e1

And you have an extra "n" in the output of your php script. I guess that was supposed to be a \n?


推荐阅读