Python hmac(sha1)计算

时间:2016-01-27 10:22:02

标签: python hmac hmacsha1

我正在尝试计算Python中的HMAC-SHA1值,但结果与我用作参考的标准工具(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())

结果:801271609151602865551107406598369208989784139177

OpenSSL的

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

结果:8c5a42f91479bfbaed8dd538db8c4a76b44ee5a9

1 个答案:

答案 0 :(得分:3)

尝试在HMAC上使用binascii.hexlify()

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

或者您可以使用str.encode('hex')

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