我已经用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 代码中,您缺少一个请求原始输出的参数。请参阅docs .
您需要将 $raw_output=true
添加到 hash_hmac
调用中,如下所示:
hash_hmac('sha256', utf8_encode($sign), utf8_encode($secret_key), , $raw_output=true)
关于php - python 和 php 中的字符串编码结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58444294/