'How to generate HMAC SHA 512 in Java?
I have to validate HMAC that I receive from webhook header.
Documenation says:
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.
What I am doing:
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);
}
I have tried many many ways of new HmacUtils argumets including byte arrays/string, different StandardCharsets, etc. Nothing worked for me...
Debugging results: All of tries generated HMAC that is not equals HMAC that I receive from webhook.
Where did I make mistake?
Solution 1:[1]
Have you tried adding to your pom.xml:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
And then use this piece of code:
String jsonBodyAsString = "{\"notificationId\":\"ff8acc67-a473-4550-8e13-da30ed54ab7d\",\"eventType\":\"net.authorize.customer.deleted\",\"eventDate\":\"2017-04-15T20:39:48.68994Z\",\"webhookId\":\"5eca3570-70a4-4293-aec1-5fa7bdf0183b\",\"payload\":{\"entityName\":\"customerProfile\",\"id\":\"1811525753\"}}";
String signatureKey = "D6D1EA140DA71FF6B7AB7D...CHANGE_TO_YOUR_SIGNATURE_KEY";
String xApiSignature = request.getHeader("X-API-Signature");
String hashOfBody = new HmacUtils(HmacAlgorithms.HMAC_SHA_512, signatureKey)
.hmacHex(jsonBodyAsString);
Boolean result = xApiSignature.equalsIgnoreCase(hashOfBody);
assertTrue(result);
I could make it work with this approach.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ACMattos |
