Carenborn Posted September 4, 2021 Share Posted September 4, 2021 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? Quote Link to comment https://forums.phpfreaks.com/topic/313662-different-hmac-hash-when-converting-python-to-php/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.