Hash Algorithm
HMAC SHA256 Algorithm Code Snippet
To generate the HMAC SHA256 checksum using Java, you can use the following code snippet:
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class HmacSha256Example {
public static void main(String[] args) {
// For example merchantId + timestamp
String merchantId = "1387a6cc-3651-4473-ae52-e415caea3395"
Long timestamp = 1709289932725;
String stringToEncode = merchantId + timestamp.toString();
String secretKey = "apikey";
String hash = calculateHmacSha256(message, secretKey);
System.out.println("Hash: " + hash);
}
private static String calculateHmacSha256(String message, String secretKey) {
String algorithm = "HmacSHA256";
try {
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(keySpec);
byte[] hmacBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hmacBytes);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
return null;
}
}
}
Make sure to replace the message variable with the concatenated parameter
values, sorted in ascending order by parameter name. Also, replace the
secretKey variable with your merchant's secret key.
This code snippet calculates the HMAC SHA256 checksum for the given message using the provided secret key. The resulting hash is then encoded in Base64 format.
Remember to include the necessary import statements and handle any exceptions that may occur during the HMAC calculation.