Webhook Hmac Verification Issue in Java

barisozdogan
Visitor
2 0 0

Hi Everyone,

I'm experiencing an issue while trying to verify webhooks within my springboot api project. I've followed all the instructions as stated in the official Manage Webhooks page, yet the calculated hmac sha256 string is not matching with the shopify provided header "x-shopify-hmac-sha256".  They are always different.

I'm using the app secret key from my (draft) app which can be seen within <shopify partners page -> apps -> my draft app" because I created my webhooks via API.

I'm using following code which I got from this github repo -> calculate-hmac-sha256  

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class HmacUtils {
    public static final String HMAC_ALGORITHM = "HmacSHA256";

    public static String calculateHmac(String message,
            String secret) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmac = Mac.getInstance(HMAC_ALGORITHM);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(), HMAC_ALGORITHM);
        hmac.init(key);
        return Base64.encodeBase64String(hmac.doFinal(message.getBytes()));
    }

    public static boolean checkHmac(String message, String hmac,
            String secret) throws InvalidKeyException, NoSuchAlgorithmException {
        return hmac.equals(calculateHmac(message, secret));
    }
}

 

I also tried different ways to achieve this however they did not work as well.

Could you please assist me, obviously i missed something here.

Thanks,

Baris

Replies 2 (2)

hitanshu88
Shopify Partner
12 1 10

You can use the below mentioned code to verify hmac value
//message is request body

String secret = "SECRET_KEY"; //This will be app secret key

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(UTF_8), "HmacSHA256"); sha256_HMAC.init(secret_key);

BinaryEncoder encoder = new Base64();

byte[] macData = sha256_HMAC.doFinal(message.getBytes(UTF_8));

String newHmac = new String(encoder.encode(macData), UTF_8);

return MessageDigest.isEqual(hmac.getBytes(UTF_8), newHmac.getBytes(UTF_8));//returns true if hmac is valid

pavankumar12579
Shopify Partner
3 0 1

I am not able to verify still using the above logic, can anyone help here