Jump to content

Different hmac hash when converting python to php


Carenborn
 Share

Recommended Posts

Hi.

Im trying to convert a Python script to PHP and I have trouble getting the same hmac hash values (hmac_signature).

Python script:

import hashlib
import hmac
import json
#Pre shared secret key
secret = "cd01985/813hip914Vnn04&1#11ai761"
#The message I will send
message = {"user_id": "Frank", "query": "Dog"}
#Output message: {'user_id': 'Frank', 'query': 'Dog'}
#Encode the secret using UTF-8
secret_encoded = secret.encode('utf-8')
#Output secret_encoded: b'cd01985/813hip914Vnn04&1#11ai761'
#Dump dict to string and encode using UTF-8
message_encoded = json.dumps(message).encode('utf-8')
#Output messag_encoded: ab742454c0158c3ec8d8c9c8965381567d45bee77e6f8d9aacb2239587285f87
#Compute the HMAC hash and convert to string of hex chars
hmac = hmac.new(secret_encoded, message_encoded, hashlib.sha256)
#Output hmac: <hmac.HMAC object at 0x000001E05BE4BE50>
hmac_signature = hmac.hexdigest()
#Output hmac_signature: ab742454c0158c3ec8d8c9c8965381567d45bee77e6f8d9aacb2239587285f87

PHP:

<?php
	//Pre shared secret key
	$secret = "cd01985/813hip914Vnn04&1#11ai761";
	//The message I will send
	$message = array(
		'user_id'=>"Frank",
		'query'=>"Dog"                              
	);
	//Output $message: Array ( [user_id] => Frank [query] => Dog )
	//Encode the secret using UTF-8
	$secret_encoded = utf8_encode($secret);
	//Output $secret_encoded: cd01985/813hip914Vnn04&1#11ai761
	//Dump dict to string and encode using UTF-8
	$message_encoded = json_encode($message);
	//Output $message_encoded: {"user_id":"Frank","query":"Dog"}
	$message_encoded = utf8_encode($message_encoded);
	//Output $message_encoded: {"user_id":"Frank","query":"Dog"}
	//Compute the HMAC hash and convert to string of hex chars
	$hmac_signature = hash_hmac('sha256', $message_encoded, $secret, false);
	//Output $hmac_signature: e4fd77b03cd58b174c3f6f0ad52a484386280289127f5fa7251df1686c3fb582
?>

Do anyone know what im doing wrong?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.