amitshekhariitbhu / Fast-Android-Networking

🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀
https://outcomeschool.com
Apache License 2.0
5.69k stars 958 forks source link

HMAC #328

Open silaros88 opened 6 years ago

silaros88 commented 6 years ago

Hello I have to hmac request to web api. Could you tell me how to do it? I've tried everything and still it can not be authenticated.

This is my Rx2AndroidNetworking call:

        java.util.Date date = new Date();

        Map<String, String> param = new HashMap<>();
        param.put("method", "info");
        param.put("time", String.valueOf(date.getTime() / 1000));

        String params = CommonUtils.getQueryString("info", String.valueOf(String.valueOf(date.getTime() / 1000))).replace("?", "");

        Rx2AndroidNetworking.post("https://api.com/api/")
                .addHeaders("key", apiKey)
                .addHeaders("hash", CommonUtils.hmacDigest(params, apiPin))
                .addUrlEncodeFormBodyParameter(param)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        return;
                    }

                    @Override
                    public void onError(ANError anError) {
                        return;
                    }
                });
    public static String hmacDigest(String msg, String keyString) {
        Mac sha256_HMAC = null;
        String hash = "";
        try {
            sha256_HMAC = Mac.getInstance("HmacSHA512");

            SecretKeySpec secretKey = new SecretKeySpec(keyString.getBytes(), "HmacSHA512");
            sha256_HMAC.init(secretKey);
            hash = Base64.encodeToString(sha256_HMAC.doFinal(msg.getBytes()), Base64.DEFAULT);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }

        return hash;
    }

What am I doing wrong?

amitshekhariitbhu commented 6 years ago

I think it can be done with some configurable okHttp. Refer this link.