如何解决尝试使用 hmac 和 sha256 验证 webhook 机密
所以我在这里有点困惑。
我正在使用一个向我的服务器发送 webhook 的 api。它允许我们验证来自 api 的请求。
我正在使用 django rest 框架。
签名就是这样过来的
Mux-Signature: t=1565220904,v1=20c75c1180c701ee8a796e81507cfd5c932fc17cf63a4a55566fd38da3a2d3d2
t= 之后的值是时间戳。 v1=后面的值就是签名
muxsecurityheader = request.Meta['HTTP_MUX_SIGNATURE']
spiltmuxsecurityheader = muxsecurityheader.split(',')
timestamp = spiltmuxsecurityheader[0]
timestamp = timestamp[2:]
receviedsignature = spiltmuxsecurityheader[1]
receviedsignature = receviedsignature[3:]
secretkey = 'a string that is my key'
payload = timestamp + '.' + str(request.body)
expectedsignature = hmac.new(secretkey,bytes(payload,'UTF-8'),hashlib.sha256).hexdigest()
print(expectedsignature)
是我目前的代码。
在 apis 文档的示例中 https://docs-legacy.mux.com/docs/webhook-security
它声明通过提供的示例确定预期的签名。显然这只是伪代码
secret = // your signing secret
payload = timestamp + "." + request_body
expected_signature = createHmacSha256(payload,secret)
这类似于我上面的代码。
但是我遇到了一些错误
expectedsignature = hmac.new(secretkey,hashlib.sha256).hexdigest()
raise TypeError("key: expected bytes or bytearray,but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray,but got 'str'
就是其中之一。
例如是我正在尝试解决的问题。而我正处于你们中的一个人会立即看到我做错了什么的地步。非常感谢您提供一些清晰的信息。
解决方法
这是解决方案。我需要把东西变成字节!
muxsecurityheader = request.META['HTTP_MUX_SIGNATURE']
spiltmuxsecurityheader = muxsecurityheader.split(',')
timestamp = spiltmuxsecurityheader[0]
timestamp = timestamp[2:]
receviedsignature = spiltmuxsecurityheader[1]
receviedsignature = receviedsignature[3:]
secretkey = 'the secret key that they gave me and stuff'
payload = bytes(timestamp,"UTF-8") + bytes('.','UTF-8') + request.body
expectedsignature = hmac.new(bytes(secretkey,'UTF-8'),payload,hashlib.sha256).hexdigest()
if expectedsignature == receviedsignature:
print('yay')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。