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

如何使用api密钥和时间戳以及sha256十六进制加密在python中创建签名,python,api,digital-signature,sha256,Python,Api,Digital Signature,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}')

这是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,然后再转换为str,问题就解决了。

导入hashlib,time

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


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

只使用字符串而不是字节?@BryceWayne我也尝试过,但没有成功。感谢您提供此代码片段,它可能会提供一些有限的即时帮助。通过展示为什么这是一个很好的问题解决方案,A将极大地提高它的长期价值,并将使它对未来有其他类似问题的读者更有用。请在您的回答中添加一些解释,包括您所做的假设。