【问题标题】:Python hmac (sha1) calculationPython hmac (sha1) 计算
【发布时间】:2016-01-27 18:44:55
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • python 输出可能是十进制表示吗?它根本不包含 A-F。
  • @Norman 确实是:>>> hex(801271609151602865551107406598369208989784139177) '0x8c5a42f91479bfbaed8dd538db8c4a76b44ee5a9'

标签: python hmac hmacsha1


【解决方案1】:

尝试在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2011-01-28
    • 1970-01-01
    • 2011-10-26
    相关资源
    最近更新 更多