php - Python3 中的 hash_hmac 和 bin2hex
问题描述
我得到了与使用和PHP
的加密函数相关的代码。逻辑很简单。我必须消化我的然后将二进制转换为十六进制字符串hash_mac
bin2hex
key
这是我的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";
PHP
:28d28fd2cecc10a5d1e98a03dbec23844780d1609e7eaedba72e7c3a8e0e84e1n
我实现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()
Python
:2e3dff89bef78489c4f42e1e54a40b257e908aaa2d1aa46b5873acb53c51c9ac
问:
我哪里错了?
解决方案
错误在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
?
推荐阅读
- html - 仅在同一滚动容器中水平或垂直修复项目
- java - ftp 功能卡住后最终无法继续?
- javascript - Javascript:没有键/名称的对象文字中的方法
- android-studio-3.1.3 - 我不小心关闭了 Android Studio 3.1.3 中的预览栏,如何找回?
- node.js - node express 能否在返回当前请求的响应之前处理下一个请求?
- android - React Native - 部署构建失败
- php - 如何使用 codeigniter 框架读取 PUT 和 DELETE 请求?
- matlab - 如何对时间序列速度信号进行小波变换
- oauth - 如何从服务器使用 Slack API 进行身份验证
- php - Laravel eloquent 无法将数据提交到数据库