【问题标题】:Python encoded message with HMAC-SHA256使用 HMAC-SHA256 的 Python 编码消息
【发布时间】:2016-11-03 04:08:19
【问题描述】:

我尝试根据instructions在python中使用HMAC-SHA256编码消息

import hmac
import hashlib

nonce = 1234
customer_id = 123232
api_key = 2342342348273482374343434
API_SECRET = 892374928347928347283473

message = nonce + customer_id + api_key
signature = hmac.new(
    API_SECRET,
    msg=message,
    digestmod=hashlib.sha256
).hexdigest().upper()

但我明白了

Traceback(最近一次调用最后一次):文件“gen.py”,第 13 行,在 digestmod=hashlib.sha256 文件“/usr/lib/python2.7/hmac.py”,第 136 行,新 return HMAC(key, msg, digestmod) File "/usr/lib/python2.7/hmac.py", line 71, in init if len(key) > blocksize: TypeError: 'long' 类型的对象没有 len()

有人知道为什么会崩溃吗?

【问题讨论】:

    标签: python api encode hmac


    【解决方案1】:

    您正在使用 api 需要字符串/字节的数字。

    # python 2
    import hmac
    import hashlib
    
    nonce = 1234
    customer_id = 123232
    api_key = 2342342348273482374343434
    API_SECRET = 892374928347928347283473
    
    message = '{} {} {}'.format(nonce, customer_id, api_key)
    signature = hmac.new(
        str(API_SECRET),
        msg=message,
        digestmod=hashlib.sha256
    ).hexdigest().upper()
    
    print signature
    

    【讨论】:

      【解决方案2】:

      如果你想在 python3 中执行,你应该执行以下操作:

      #python 3
      import hmac
      import hashlib
      
      nonce = 1
      customer_id = 123456
      API_SECRET = 'thekey'
      api_key = 'thapikey'
      
      message = '{} {} {}'.format(nonce, customer_id, api_key)
      
      signature = hmac.new(bytes(API_SECRET , 'latin-1'), msg = bytes(message , 'latin-1'), digestmod = hashlib.sha256).hexdigest().upper()
      print(signature)
      

      【讨论】:

      • 为什么使用 latin-1?
      • signature = hmac.new(bytes(API_SECRET , 'utf-8'), msg = bytes(message , 'utf-8'), digestmod = hashlib.sha256).hexdigest().upper()
      猜你喜欢
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 2018-07-05
      • 2017-02-07
      • 2021-07-10
      • 2017-11-30
      • 1970-01-01
      相关资源
      最近更新 更多