Skip to main content
 首页 » 编程设计

python之在 python 3 中生成 HMAC Sha256

2024年12月31日9lvdongjie

我编写代码以向我们的 API 验证带有 JSON 的 HMAC Auth 传入 POST 请求。我收到的 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")