如何使用api密钥和时间戳在python中创建签名并进行sha256十六进制加密

问题描述

这是api文档中提供的示例代码

#!/bin/bash 
apiKey="yourApiKey"
secret="yourSecret"
curl -i \
-X GET \
-H 'Accept:application/json' \
-H 'Api-key:'$apiKey'' \
-H 'X-Signature:'$(echo -n ${apiKey}${secret}$(date +%s)|sha256sum|awk '{ print $1}')'' \
https://api.test.hotelbeds.com/hotel-api/1.0/status

这是我在python中所做的:

secret = b"Secret key"
apikey = b"Api key"
dateNow = str(datetime.datetime.Now().timestamp())
dateNow = bytes(dateNow,'utf-8')

sig = apikey + secret + dateNow

hash = hashlib.sha256(sig).hexdigest()

但是,我收到验证错误。有人可以帮我修复我的代码吗?

解决方法

通过将日期转换为int和int然后转换为str来解决问题。

,

导入hashlib,时间

string = str(API_KEY).strip()+ str(SECRET).strip()+ str(int(time.time()))。strip()

signature = hashlib.sha256(string.encode())。hexdigest()