3

I am coding an android app that using sha256 encryption. I try using

String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes())); 

But I I got a runtime error say java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String. I researched the issue and someone on stack suggested that android as an older version of the org.apache.commons.codec.binary.Base64 implemented and there is a conflict between the version I am using and the the one that android implements so that why that method Base64.encodeBase64String is not found. here is the link to what i found as help java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application. The solution was to use

String hash = new String(Base64.encodeBase64(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));

I did use that and it seems to work but because the has that I am getting does not match what the server I am working with is expecting. I am wondering if the two are truly equivalent.

I used this link to implement the sha256 http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/#java

Here is my code I am using retrofit library for http method calls:

public static String ComputeHash(String[] dataArray, String privateKey) {

    String hash="";

    String data = "";

    for (String item : dataArray) {
        data += item;
    }

    try {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(privateKey.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        //hash = Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes()));
        //hash = Base64.encodeToString(sha256_HMAC.doFinal(data.getBytes("UTF-8")), Base64.DEFAULT);
        hash = new String(Base64.encodeBase64(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));

    } catch (Exception e) {
        Toast.makeText(MyApplication.getAppContext(), "Error", Toast.LENGTH_LONG).show();
    }
    return hash;
}

public <S> S createService(Class<S> serviceClass){

    stamp = String.valueOf(System.currentTimeMillis() / 1000);//get the number of seconds since the epoch

    String[] data = new String[]{"thisisatestpublickey", 1438915015+"", "GET"};
    expectedSignature = ComputeHash(data, "thisistestprivatekey");

    RequestInterceptor requestInterceptor = new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("Authorization", "Basic YXZlbmdlcnM6bWlnaHR5bWluZHM=");
            request.addHeader(ApplicationConstants.PublicKeyHeaderName, "thisisatestpublickey");
            request.addHeader(ApplicationConstants.StampHeaderName, 1438915015+"");
            request.addHeader(ApplicationConstants.SignatureHeaderName, expectedSignature);

        }
    };


}
Community
  • 1
  • 1
Castell James
  • 329
  • 6
  • 23

0 Answers0