Arshad Ameen
Arshad Ameen

Reputation: 259

Different string encoding results in python and php

I have encoded the string in python and, got the expected result. And then I tried the same logic in PHP, but I got different results. I need to get the expected result (Python result) in PHP.

Please, anyone, help me to get this result. Thanks

Below is my Python code

    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='

My PHP Code is below

    <?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);
    ?>

Upvotes: 1

Views: 188

Answers (1)

Sebastian Kreft
Sebastian Kreft

Reputation: 8199

In your PHP code you are missing an argument to ask for raw output. See the docs.

You need to add $raw_output=true to your hash_hmac call as in:

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

Upvotes: 1

Related Questions