首页 > 解决方案 > 不同的字符串编码导致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);
    ?>

标签: phppython

解决方案


在您的 PHP 代码中,您缺少一个要求原始输出的参数。请参阅文档

您需要添加$raw_output=true到您的hash_hmac通话中,如下所示:

hash_hmac('sha256', utf8_encode($sign), utf8_encode($secret_key), , $raw_output=true)

推荐阅读