php - 不同的字符串编码导致python和php
问题描述
我已经在 python 中对字符串进行了编码,并得到了预期的结果。然后我在 PHP 中尝试了相同的逻辑,但得到了不同的结果。我需要在 PHP 中得到预期的结果(Python 结果)。
请任何人帮助我得到这个结果。谢谢
下面是我的 Python 代码
import hmac
import base64
import requests
import json
import time
time='1571373466.733'
base_url = 'https://www.test.com'
request_path = '/api/account'
api_key='f343faf6-70d8-46db-a04d-1142304e3551'
secret_key= '7C73595142C6CB7A016A7B0D4D6EA24C'
passphrase= 'tVLd8b2xdoLOKCpc2adfIKE'
timestamp=time
body=''
method='GET'
message = str(timestamp) + str.upper(method) + request_path + str(body)
mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
d = mac.digest()
print(base64.b64encode(d)) # I want to get this same result in PHP
# result is : b'+Ek2Tel8H0GxWELhNnI/MdsQI4+GpLzZWHAkjzh/NFI='
我的 PHP 代码如下
<?php
$endpoint='https://www.test.com';
$request_path ='/api/account';
$api_key='f343faf6-70d8-46db-a04d-1142304e3551';
$secret_key= '7C73595142C6CB7A016A7B0D4D6EA24C';
$passphrase= 'tVLd8b2xdoLOKCpc2adfIKE';
$timestamp='1571373466.733';
$body='';
$method='GET';
$sign=$timestamp.$method.$request_path.$body;
$sign = utf8_encode(base64_encode(hash_hmac('sha256', utf8_encode($sign), utf8_encode($secret_key))));
print_r($sign);
?>
解决方案
在您的 PHP 代码中,您缺少一个要求原始输出的参数。请参阅文档。
您需要添加$raw_output=true
到您的hash_hmac
通话中,如下所示:
hash_hmac('sha256', utf8_encode($sign), utf8_encode($secret_key), , $raw_output=true)
推荐阅读
- python - 从菜单模式和终端模式运行时,CUDA 结果不同
- azure - Azure ARM 模板参数文件中的函数无法正常工作
- python - 删除尚未出现在另一个数据框中的数据框
- vue.js - axios get 方法不会显示任何结果
- allure - 如何通过从数据库中提取测试结果将 Allure 测试结果推送到数据库并生成 Allure 仪表板
- python - 如何移动到下一个 YouTube 视频并收集有关推荐视频的数据?
- tensorflow.js - node.js 中的 TensorFlow QNA 模型返回空数组
- python - 为什么这会给我 InvalidArgumentError?
- javascript - 使用 React 和 Redux 实现文本过滤的正确方法是什么?
- r - 如何计算 t.-statistic 值并使用 R 找到两侧 P 值?