【问题标题】:How to create a signature in python using an api key and timestamp, with sha256 hex encryption如何使用 api 密钥和时间戳在 python 中创建签名,并使用 sha256 十六进制加密
【发布时间】:2020-12-16 23:08:08
【问题描述】:

这是 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()

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

【问题讨论】:

  • 只使用字符串而不是字节?
  • @BryceWayne 我也试过了,但没用。

标签: python api digital-signature sha256


【解决方案1】:

问题是通过将日期转换成int再转换成str来解决的。

【讨论】:

    【解决方案2】:

    导入 hashlib,时间

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

    签名= hashlib.sha256(string.encode()).hexdigest()

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多