如何在 Java 中生成 HMAC SHA 512?

时间:2021-04-29 19:34:41

标签: java encoding hmac

我必须验证从 webhook 标头收到的 HMAC。

文档说: API uses HMAC (hash-based message authentication code) with the SHA-512 hash function for additional authentication. To validate against X-API-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.

我在做什么:

public String getHMACHashString(String body) throws UnsupportedEncodingException {
  return 
       new HmacUtils(HMAC_SHA_512, String.valueOf(Hex.encodeHex(this.webhookSecret.getBytes())))
       .hmacHex(body.getBytes());
}

public boolean isValidHMAC(String body, String externalHMAC) throws UnsupportedEncodingException {
    return this.getHMACHashString(body).equals(externalHMAC);
  }

我尝试了很多 new HmacUtils 参数的方法,包括字节数组/字符串、不同的 StandardCharsets 等。没有任何对我有用...

调试结果: 所有尝试生成的 HMAC 都不等于我从 webhook 收到的 HMAC。

我哪里做错了?

0 个答案:

没有答案
相关问题