PHP hash_hmac 转 JS Hmac

问题描述

我正在尝试验证 webhook 签名,我从 api2cart 的文档中获得了此 PHP 代码,但我需要在 Javascript 中使用它。我尝试过但我无法匹配签名和 HMAC 生成的值,更多详细信息here

要遵循的步骤:

  1. 收集所有以“X-Webhook-”开头的headers // 我在header中以x-webhook-的形式接收,不知道是否影响加密

  2. 从数组中删除“X-Webhook-Signature”。

  3. 按键的字母顺序对标题进行排序

  4. 将标头编码为 JSON。

  5. 连接字符串,JSON 头字符串应该在前

  6. 使用 HMAC SHA256 函数对结果字符串进行哈希处理,输出原始二进制数据集为 true (raw_output = true)

使用您的 store_key 作为密钥生成二进制签名

  1. 对字符串进行 Base64 编码

$headersForjson = [
'X-Webhook-Error-Code' => '0','X-Webhook-Action' => 'update','X-Webhook-Timestamp' => '1516291592','X-Webhook-Entity' => 'product','X-Webhook-Store-Id' => '1','X-Webhook-Signature' => 'SGVsbG8gd2l0aCBBUEkyQ2FydA==',];

$signatureFromrequest = $headersForjson['X-Webhook-Signature'];

unset($headersForjson['X-Webhook-Signature']);

ksort($headersForjson);

$headers = json_encode($headersForjson);

$data = $headers . $params['raw_body'];

$generatedSignature = base64_encode(hash_hmac('sha256',$data,$storeKey,true));

 if (hash_equals($signatureFromrequest,$generatedSignature)) {
   return true;
 }

这是我所做的:

const signature = headers['x-webhook-signature'];
delete headers['x-webhook-signature'];
    // the header contained other keys I had to get keys starting with x-webhooks
    let xkeys = Object.keys(headers).filter(key => key.includes('x-webhook-')).sort();
    let xheaders = JSON.stringify(xkeys.reduce((res,key) => Object.assign(res,{ [key]: headers[key] }),{}));
    let data = xheaders + rawBody


const generatedHash = createHmac('SHA256',"SecretKey")
            .update(data,'utf-8')
            .digest('base64');


return generatedHash === signature

在这里错过了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)