HMAC-SHA256 issue in Shopify oauth (Output does not match)

て烟熏妆下的殇ゞ 提交于 2019-12-04 18:30:48

The example is wrong apparently. Your hash code is OK. You'll need to make sure you include all parameters from the Shopify response e.g. the input for verification of a response would look like:

code={code}&protocol=https://&store={store}&timestamp={timestamp}

See: https://ecommerce.shopify.com/c/shopify-apis-and-technology/t/you-broke-my-build-hmac-verification-broken-282951

Here's the java code you need to verify Shopify HMAC. The protocol parameter isn't required unless it was in the result from shopify, which it wasn't from me.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String HMAC_ALGORITHM = "HmacSHA256";
    resp.setContentType("text/html;charset=UTF-8");
    Map<String,String[]> parameters = req.getParameterMap();
    String data = null;
    SortedSet<String> keys = new TreeSet<String>(parameters.keySet());
    for (String key : keys) {
        if (!key.equals("hmac")&&!key.equals("signature")){
        if (data == null){
            data = key + "=" +req.getParameter(key);
        }
            else {
            data = data + "&" + key + "=" + req.getParameter(key);
        }
    }
    }
    SecretKeySpec keySpec = new SecretKeySpec(SHARED_KEY.getBytes(),HMAC_ALGORITHM);
    Mac mac = null;
    try {
        mac = Mac.getInstance(HMAC_ALGORITHM);
        mac.init(keySpec);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        if (Hex.encodeHexString(rawHmac).equals(req.getParameter("hmac"))){
            //THE HMAC IS VERIFIED
        } else {
            //THE HMAC IS NOT VERIFIED
        }
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        e.printStackTrace();
    }
}

Interestingly, the timestamp parameter in data turns into

×tamp=1459537704

instead of

&timestamp=1459537704

here is my prod code:

public class HMACValidator {

   public static String sha256HMAC(String key, String data) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, DecoderException {
    Mac hmac = Mac.getInstance("HmacSHA256");
    System.out.println("data "+data);
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    hmac.init(secret_key);
    return Hex.encodeHexString(hmac.doFinal(data.getBytes("UTF-8")));
    }

    public static boolean validateShopifyAskForPermission(String key, String hmac, String shop, String timestamp) throws Exception {
        return (sha256HMAC(key, "shop="+shop+"&timestamp="+timestamp).compareTo(hmac) == 0);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!