1

i need to configurate payments in client application. In order to do that i need to generate signature (sha256) using private key. In payments documentation there is function in php to generate signature:

function createSignature($orderData, $serviceKey, $hashMethod)
{
$data = prepareData($orderData);
return hash($hashMethod, $data . $serviceKey);
}

So they use build in php function hash. Unfortunately we have application in java and i need to make same function in java, i have some string as input data and private key. I found solutions in java e.g:

 public static String encode(String key, String data) throws Exception {
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    sha256_HMAC.init(secret_key);

    return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}

But in php and in java i receive different hash. How to create same function in java as in php?

  • "How to create same function in java as in php?" - Do you know what the `hash` function in PHP is doing? – Jeff Scott Brown Mar 23 '21 at 18:56
  • The php function is an ad-hoc MAC, not a standard MAC. As such, simply duplicate the php method using the Java MessageDigest class. – President James K. Polk Mar 23 '21 at 18:57
  • to be honest i do not know how php function works, i am java developer but unfortunately documentation is written in php :(. President James K. Polk could you paste ready function? i am not sure what you mean – Jacek Kaczmarek Mar 23 '21 at 18:59
  • 1
    You don't need to replicate the whole `hash` function, you just need to perform a [SHA256 hash](https://stackoverflow.com/a/5531479/231316). Also, in PHP `.` is the concatenation operator. – Chris Haas Mar 23 '21 at 19:17
  • There's a big difference between your two code samples in how they are handling the key. In PHP, your key is simply being appended to the end of your data, and the combined string is then hashed. In your Java, a SHA256 HMAC will combine the key and data in a completely different way. – codebod Mar 23 '21 at 20:42
  • what do you mean appended? – Jacek Kaczmarek Mar 23 '21 at 22:08

1 Answers1

0

Solution was that i needed to append serviceKey in java at the end of the variable String data and use hashing function from Guava Library(https://www.baeldung.com/sha-256-hashing-java)

  String key = "amount=" + amountX +"&currency=" + "PLN" + "&customerEmail=" + user.getEmail() + "&customerFirstName=" + user.getFirstname() +
    "&customerLastName=" + user.getLastname() + "&merchantId=" + merchantId + "&orderId=" + session + "&serviceId=" + serviceId + servicekey;

  
    String sha256hex = Hashing.sha256()
            .hashString(key, StandardCharsets.UTF_8)
            .toString();

Now it works!