代码之家  ›  专栏  ›  技术社区  ›  user982124

PHP将简单的三行JavaScript转换为等效的PHP

  •  0
  • user982124  · 技术社区  · 5 年前

    我已经得到了几行JavaScript,我需要将它们转换成PHP等价物。我不是一个JavaScript开发人员,我正在努力解决这个问题。以下是我收到的JavaScript示例:

    const crypto = require('crypto')
    const secret_in_hex = Buffer.from(secret, 'hex');
    
    const hash = crypto.createHmac('sha512', secret_in_hex)
      .update(body)
      .digest('hex')
    
    // Compare hash with the received X-Onfleet-Signature in raw bytes
    

    这个 docs

    Each webhook request contains a signature from Onfleet in X-Onfleet-Signature header. To authenticate the webhook request received on your webhook server, you will need to validate against this header. To validate against X-Onfleet-Signature, you will need to compare its value with an HMAC you have generated using the hexadecimal format of your webhook secrets and the full body of the webhook POST request in raw bytes.

    我想我会用 hash_hmac 功能和可能的 bin2hex 函数,但在这一点上完全难倒了,如果有人能向我展示上述JavaScript的PHP等价物,我将不胜感激(假设有)。

    0 回复  |  直到 5 年前
        1
  •  0
  •   Clement Sam    5 年前

    最简单的等价物应该是:

    $secretInHex = hex2bin($secret);
    $hash = hash_hmac('sha512', $body, $secretInHex);
    

    你应该注意到 hex2bin 功能 不将十六进制数转换为二进制数,但对十六进制编码的二进制字符串进行解码 .

    所以提供的秘密应该已经是十六进制了 hex2bin 将引发异常

    推荐文章