使用HMAC-SHA256的Python编码消息

使用HMAC-SHA256的Python编码消息,python,api,encode,hmac,Python,Api,Encode,Hmac,我尝试使用python中的HMAC-SHA256根据 但我明白了 回溯(最后一次调用):文件“gen.py”,第13行,在 digestmod=hashlib.sha256文件“/usr/lib/python2.7/hmac.py”,第136行,新格式 返回HMAC(key,msg,digestmod)文件“/usr/lib/python2.7/HMAC.py”,第71行,在init 如果len(key)>blocksize:TypeError:long类型的对象没有len() 有人知道为什么会

我尝试使用python中的HMAC-SHA256根据

但我明白了

回溯(最后一次调用):文件“gen.py”,第13行,在 digestmod=hashlib.sha256文件“/usr/lib/python2.7/hmac.py”,第136行,新格式 返回HMAC(key,msg,digestmod)文件“/usr/lib/python2.7/HMAC.py”,第71行,在init 如果len(key)>blocksize:TypeError:long类型的对象没有len()


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

您使用的是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

如果要在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)

为什么使用拉丁语-1?
#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)