Python encoded message with HMAC-SHA256

Oan*_*one 4 python api encode hmac

I try to encoded message with HMAC-SHA256 in python according to instructions

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()
Run Code Online (Sandbox Code Playgroud)

but I get this

Traceback (most recent call last): File "gen.py", line 13, in digestmod=hashlib.sha256 File "/usr/lib/python2.7/hmac.py", line 136, in new return HMAC(key, msg, digestmod) File "/usr/lib/python2.7/hmac.py", line 71, in init if len(key) > blocksize: TypeError: object of type 'long' has no len()

Does anyone have any idea why crashes?

nun*_*usa 31

如果你想在 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)
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用latin-1? (13认同)
  • `signature = hmac.new(bytes(API_SECRET,'utf-8'), msg = bytes(message,'utf-8'),digestmod = hashlib.sha256).hexdigest().upper()` (3认同)

Rz *_* Mk 6

您正在使用数字,而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
Run Code Online (Sandbox Code Playgroud)