在python 3中生成HMAC Sha256

在python 3中生成HMAC Sha256,python,rest,api,webhooks,hmac,Python,Rest,Api,Webhooks,Hmac,我编写代码,用JSON向API验证HMAC Auth传入POST请求。我收到的HMAC是od5zxl4tdgwr78e9vo3cyrjuoft8wortbttiuuuih1pq= 当我尝试自己使用Python生成它时,它总是不同的 以下是我收到的JSON请求: { "shipper_id": 4841, "status": "Cancelled", "shipper_ref_no": "", "tracking_ref_no": "", "shipper_

我编写代码,用JSON向API验证HMAC Auth传入POST请求。我收到的HMAC是
od5zxl4tdgwr78e9vo3cyrjuoft8wortbttiuuuih1pq=

当我尝试自己使用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"
}
而客户端密码是
817a372317f4c7fac24b1f1b324bbab

我收到的HMAC机密是
od5zxl4tdgwr78e9vo3cyrjuoft8wortbttiuuuih1pq=

以下是我用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
?>


但是我不知道如何在Python3中做到这一点。

在Python3中,您基本上需要以下内容,这些内容取自您处理GitHub webhook请求的方式

from collections import OrderedDict

params = orderedDict()

params["shipper_id"] = 4841
params["status"] = "Cancelled"
params["shipper_ref_no"] = ""
params["tracking_ref_no"] = ""
params["shipper_order_ref_no"] = ""
params["timestamp"] = "2018-05-23T15:13:28+0800"
params["id"] = "61185ecf-3484-4985-b625-ffe30ba36e28"
params["previous_status"] = "Pending Pickup"
params["tracking_id"] = "NVSGBHINK000000001"
mes = json(params, separator = (";",",")).highdigest()
sighnature = hmac.new(mes, sha256)
# separators = (";",",") - i'm not shure
params['sighnature'] = sighnature
r = response.post(url,params,sighnature)
print(r.text())
    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")