首页 > 解决方案 > 在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 中做到这一点。

标签: pythonrestapiwebhookshmac

解决方案


在 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")

推荐阅读