27

I want to forward my visitors to a 3rd party paysite. This 3rd party will process their payment and POST to me a 64 character token generated from a unique order number and shared password using PHP's hash_hmac using the sha256 algorithm, like so:

$token = hash_hmac("sha256", "12345", "sharedpassword");

Then I want to use the same algorithm on my end to generate the (hopefully) the same token to verify the user has paid. The problem is I cannot find an equivalent function or way to replicate the function in Python. The closest I've come is Python's hashlib, but there doesn't appear to be a function that can take in 2 arguments - the data and the shared password. Does anyone know of an equivalent of hash_hmac that would be applicable in this case?

kshen
  • 525
  • 2
  • 9
  • 17

1 Answers1

59

You want hmac.

hmac.new("sharedpassword", "12345", hashlib.sha256).hexdigest()

or in python 3:

hmac.new(bytes("sharedpassword", 'UTF-8'), "12345".encode(), hashlib.sha256).hexdigest()
JMW
  • 7,151
  • 9
  • 30
  • 37
Amber
  • 507,862
  • 82
  • 626
  • 550
  • 1
    Thank you! I guess my google-fu needs honing. – kshen Mar 11 '12 at 03:39
  • 1
    I get a TypeError for this code `raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) TypeError: key: expected bytes or bytearray, but got 'str'` on Python 3.8.5 – jeppoo1 Dec 31 '20 at 09:47
  • 2
    @jeppoo1 This answer is 8+ years old and was written for Python 2; in Python 3 you'd pass a bytes object instead of a string. – Amber Jan 03 '21 at 21:52