views:

419

answers:

2

What is the Python equivalent of following Perl code?

hmac_md5_hex($login . "^" . $seq . "^" . $time . "^" . $amo . "^", $CryptoKey);

The Python hashlib.md5 doesn't seem to take an "cryptographic key" argument. It only accepts 1 argument.

+9  A: 

You have to use the hmac module together with md5 or sha. Per default it uses md5:

In [1]: import hmac, hashlib
In [2]: hmac.new('key', 'msg').hexdigest()
Out[2]: '18e3548c59ad40dd03907b7aeee71d67'
In [3]: hmac.new('key2', 'msg').hexdigest()
Out[3]: 'a4bde113179bc2a7c6ac9ad7309ea073'
In [4]: hmac.new('key', 'msg', hashlib.sha256).hexdigest()
Out[4]: '2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628'

Your example would probably look something like:

hmac.new(CryptoKey, '^'.join([login, seq, time, amo]), hashlib.md5).hexdigest()
unbeknown
+1 for using hashlib instead of the deprecated md5/sha modules
DNS
+4  A: 

Take a look at this python library documentation about hmac

What you probably want is:

import hmac
hmac_object = hmac.new(crypto_key)
hmac_object.update('^'.join([login, seq, time, amo, ''])
print hmac_object.hexdigest()

It's probably best to use .update() since that way you don't have to instantiate the hmac class everytime and it's a serious performance boost if you want to have a lot of hex digest of the message.

mpeterson