Search code examples
pythonhmachmacsha1

Python hmac (sha1) calculation


I am trying to calculate the HMAC-SHA1 value in Python, but results don't match with the standard tool I am using as reference (openSSL):

Python

k = "ffffffffffffffffffffffffffffffff"
m = "ffffffffffffffffffffffffffffffff"
key = k.decode("hex")
msg = m.decode("hex")
print xlong(hmac.new(key, msg=msg, digestmod=hashlib.sha1).digest())

Result: 801271609151602865551107406598369208989784139177

OpenSSL

echo -n ‘ffffffffffffffffffffffffffffffff’ | xxd -r -p | openssl dgst -sha1 -mac HMAC -macopt hexkey:ffffffffffffffffffffffffffffffff

Result: 8c5a42f91479bfbaed8dd538db8c4a76b44ee5a9


Solution

  • Try using binascii.hexlify() on the HMAC:

    >>> from binascii import hexlify
    >>> print hexlify(hmac.new(key, msg=msg, digestmod=hashlib.sha1).digest())
    8c5a42f91479bfbaed8dd538db8c4a76b44ee5a9
    

    Or you may just use str.encode('hex'):

    >>> print hmac.new(key, msg=msg, digestmod=hashlib.sha1).digest().encode('hex')
    8c5a42f91479bfbaed8dd538db8c4a76b44ee5a9