Skip to content

Instantly share code, notes, and snippets.

@motin
Last active September 15, 2021 21:41
Show Gist options
  • Save motin/7cbe1ae77bf493e3cae8 to your computer and use it in GitHub Desktop.
Save motin/7cbe1ae77bf493e3cae8 to your computer and use it in GitHub Desktop.
PHP equivalent of hmac.new(secret, message, hashlib.sha256).hexdigest()
<?php
$message = 'Message';
$secret = 'secret';
print "php\n";
print hash_hmac('SHA256', $message, $secret) . "\n";
import hmac
import hashlib
message = 'Message'
secret = 'secret'
print 'python'
print hmac.new(secret, message, hashlib.sha256).hexdigest()
$ python bin/hmac-sign.py && php bin/hmac-sign.php
python
aa747c502a898200f9e4fa21bac68136f886a0e27aec70ba06daf2e2a5cb5597
php
aa747c502a898200f9e4fa21bac68136f886a0e27aec70ba06daf2e2a5cb5597
@LazukinPavel
Copy link

In python3 secret and message should be bytecoded before passed to hmac.new()

@knoxtechnology
Copy link

knoxtechnology commented Jun 25, 2019

I have a python3 script that works to call an API, but I need to reproduce in PHP as it will be used in a wordpress site and calling out to run a python script is proving difficult on my client's (godaddy) server.

`unixtime = time.time()
body = '{"timestamp":' + str(unixtime) + '}'
 
secretBytes = bytearray.fromhex(secret)

bodyBytes = bytearray(body, "utf8")

signature = hmac.new(secretBytes, bodyBytes, digestmod=hashlib.sha256).hexdigest()`

the php equivalent hash_hmac() isn't working. Thoughts?

@vsoup
Copy link

vsoup commented Sep 15, 2021

@knoxtechnology I know it's been a while but did you ever find a solution for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment