John Davidson

php - Hash function in java

0 comments
Message:


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?



My Answer:
To create the same function in Java as in PHP, you need to ensure that you are using the same hashing algorithm and encoding for the data and key. In the PHP code, the hash method used is specified by the $hashMethod parameter, so make sure you are using the same hashing algorithm in your Java code.

In the PHP code, the data is prepared before hashing using the prepareData function. Make sure you are also preparing the data in the same way in your Java code before hashing it.

Here is an example of how you can modify your Java code to match the PHP function:

java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;

public static String createSignature(String orderData, String serviceKey, String hashMethod) throws Exception {
String data = prepareData(orderData);
Mac sha256_HMAC = Mac.getInstance(hashMethod);
SecretKeySpec secret_key = new SecretKeySpec(serviceKey.getBytes("UTF-8"), hashMethod);
sha256_HMAC.init(secret_key);

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

private static String prepareData(String orderData) {
// Implement your data preparation logic here
return orderData;
}


Make sure to replace the prepareData method with the actual data preparation logic used in the PHP code. Also, ensure that the hash method and encoding used in the Java code match the ones used in the PHP code. With these modifications, the Java function should generate the same signature as the PHP function.

Rate this post

5 of 5 based on 8317 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us