Search code examples
pythonhashsha1hmac

How can I SHA1-HMAC a string in Python


I've been trying to figure out how to use HMAC to hash a string in Python for a TOTP generator I've already made in PHP. In PHP, I use the command echo -n "0x00000000035362f9" | xxd -r -p | openssl dgst -sha1 -mac HMAC -macopt hexkey:0080700040024c8581c2 which returns the desired value 7289e7b135d54b86a462a53da93ef6ad28b902f8. However, when I use the hmac library in Python 3.10

from hashlib import sha1
from hmac import new

key = "00000000035362f9"
msg = "0080700040024c8581c2"

byte_key = bytes(key, "UTF-8")
message = msg.encode()

print(new(byte_key, message, sha1).hexdigest())
print(new(message, byte_key, sha1).hexdigest())

The printed values are b05fe172b6a8a20767c18e1bfba159f0ea54c2bd and 0fe109b32b17aeff840255558e6b5c8ff3d8a115, neither match what I want.

I've tried making the key and message hex values first, I've made them raw bytes using b'0080700040024c8581c2', encoding them using UTF-8 and ASCII, and none of the solutions have worked.

I've looked at other post relating to this, and none of them worked.
Python hmac (sha1) calculation
Python HMAC OpenSSL equivalent
hmac returning different hexdigest values to openssl
Why Python and Node.js's HMAC result is different in this code?
Implementing SHA1-HMAC with Python


Solution

  • @jasonharper's answer from the comments was correct.

    from hashlib import sha1
    from hmac import new
    from binascii import unhexlify
    
    msg = unhexlify("00000000035362f9")
    key = unhexlify("0080700040024c8581c2")
    
    print(new(key, msg, sha1).hexdigest())