Q:

PHP to Python3 HMAC signature not resulting in the same signature

I have been trying to convert a php script to a python3 script and have been failing to send through a successful signature after troubleshooting through the issue.
The below PHP example code successfully goes through so I've copied the sent timestamp and signature to try and replicate it in my python3 code. 
PHP Code
<?
    $nonce = "2015-10-26 04:53:49 EDT";
    $secret = "mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks";

    $req = array();
    $req['t'] = $nonce;
    $req['secret'] = $secret;

    $post_data = json_encode($req);
    $post_data = bin2hex($post_data);
    $sign = hash_hmac("sha256", $post_data, $secret);

    print($sign);

?>

Python 3 Code
import json
import hmac
import binascii
import hashlib

nonce = "2015-10-26 04:53:49 EDT"
secret = "mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks"

payload = {}
payload["t"] = nonce
payload["secret"] = secret

payload_json = json.dumps(payload)
post_data = binascii.b2a_hex(payload_json.encode('utf-8'))
sign = hmac.new(bytes(secret, "utf-8"), post_data, hashlib.sha256).hexdigest()

print(sign)

Based on the successful request using PHP my signature should be:
'c30ddc5878ff7b1a9b1c9078ccbdc38afef25ed510681a3d3bfc56f6c9e2f26a'

Instead I'm getting:
'f9fc8749389137252e7f207468d88a5c871110403ec533496720efd715541ec2'

Any help troubleshooting this issue would be greatly appreciated as I'm new to Python.

A:

Your problem is that by default, Python inserts spaces into the JSON string. Output of the PHP json_encode($req):
{"t":"2015-10-26 04:53:49 EDT","secret":"mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks"}

Output of the Python json.dumps(payload):
{"t": "2015-10-26 04:53:49 EDT", "secret": "mkdaklmdflfkdsmaflkdmsfdkasmfdsmflks"}

You can fix this by specifying separators, i.e.:
json.dumps(payload, separators=(',', ':'))

Also, you can control the order of the elements by using OrderedDict instead of a plain dictionary:
from collections import OrderedDict

payload = OrderedDict()

