python - 在python 3中生成HMAC Sha256
问题描述
我编写代码来验证带有 JSON 的 HMAC Auth 传入 POST 请求到我们的 API。我收到的 HMAC 是OD5ZxL4tdGgWr78e9vO3cYrjuOFT8WOrTbTIuuIH1PQ=
当我尝试使用 Python 自己生成它时,它总是不同的。
这是我收到的 JSON 请求:
{
"shipper_id": 4841,
"status": "Cancelled",
"shipper_ref_no": "",
"tracking_ref_no": "",
"shipper_order_ref_no": "",
"timestamp": "2018-05-23T15:13:28+0800",
"id": "61185ecf-3484-4985-b625-ffe30ba36e28",
"previous_status": "Pending Pickup",
"tracking_id": "NVSGBHINK000000001"
}
而客户端的秘密是817a3723917f4c7fac24b1f1b324bbab
.
我收到的 HMAC 秘密是OD5ZxL4tdGgWr78e9vO3cYrjuOFT8WOrTbTIuuIH1PQ=
.
这是我用 PHP 编写时的代码:
<?php
define('CLIENT_SECRET', 'my_shared_secret');
function verify_webhook($data, $hmac_header){
$calculated_hmac = base64_encode(hash_hmac('sha256', $data, CLIENT_SECRET, true));
return ($hmac_header == $calculated_hmac);
}
$hmac_header = $_SERVER['X-NINJAVAN-HMAC-SHA256'];
$data = file_get_contents('php://input');
$verified = verify_webhook($data, $hmac_header);
error_log('Webhook verified: '.var_export($verified, true)); //check error.log to see result
?>
但我不知道如何在 Python 3 中做到这一点。
解决方案
在 Python 3 中,您基本上需要以下内容,取自您处理 GitHub webhook 请求的方式。
import hashlib
import hmac
secret = 'CLIENT_SECRET'
data = rsp.content # assumes you're using requests for data/sig
signature = rsp.headers['X-Something-Signature']
signature_computed = 'sha1=' + hmac.new(
key=secret.encode('utf-8'),
msg=data.encode('utf-8'),
digestmod=hashlib.sha1
).hexdigest()
if not hmac.compare_digest(signature, signature_computed):
log("Invalid payload")
推荐阅读
- ionic3 - Ionic 3 本地通知只触发最后一个
- mysql - MySQLSyntaxErrorException:您的 SQL 语法有错误(Spring Hibernate)
- powershell - 通过 Powershell 设置默认域
- python - python中的“in”关键字是如何工作的?有更快的方法吗?
- c# - 如何将 XAML 文本框绑定到另一个文本框的输入或它自己的输入,然后将输入保存到 MVVM 中的数据对象?
- python-3.x - 无法在任何 IDE 中保存 python 文件
- python-3.x - 如何“临时禁止”使用 discord.py 的人?
- java - 尝试在空对象引用 Radio Group 上调用虚拟方法
- java - Line类intersectionWith方法实现
- sql - 需要根据 csv 文件中的数据填充表格