Dima Tisnek
Dima Tisnek

Reputation: 11781

Build HMAC-SHA-512 from pycrypto and hashlib

I'm trying to construct HMAC-SHA-512 from older version of pycrypto and hashlib. The result is different from test vector in RFC4231

My code so far:

from hashlib import sha512  # my pycrypto doesn't have SHA
from Crypto.Hash import HMAC
from binascii import a2b_hex

# helper to match HMAC signature
class Sha512:
    @staticmethod
    def new():
        return sha512()

def hmac(hexkey, hexdata):
    return HMAC.new(a2b_hex(hexkey), a2b_hex(hexdata), digestmod=Sha512).hexdigest()

hmac("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265")
'9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a'

# should be
'87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854'

Did I go wrong somewhere? Could there be different semantic for key in pycrypto?

Edit: I see same discrepancy in Python3 with newest pycrypto too.

Upvotes: 1

Views: 743

Answers (1)

Dima Tisnek
Dima Tisnek

Reputation: 11781

It turns out that pycrypto wants to see block and digest size of the algorithm before the latter is instantiated.

Here's a hack that works:

class Test:
    @staticmethod
    def new():
        return sha512()
    block_size = sha512().block_size
    digest_size = sha512().digest_size

Additionally, older versions of pycrypto did not support larger block sizes: https://bugs.launchpad.net/pycrypto/+bug/754806

Also, pycrypto is not really necessary for this specific task. Python provides an hmac module that happily accepts hashlib hashes.

Upvotes: 1

Related Questions