HmacUtil - Sha512 - For Bpay Only
Sample codes for reference - To generate HMAC for the header
JAVA - Implementation
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.Base64;
public class HMACUtil {
private HMACUtil() {}
public static String calculateHMAC(String signatureKey, String textToHash) {
try {
byte[] signatureKeyInByteArray = hexStringToByteArray(signatureKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(signatureKeyInByteArray, "HmacSHA512");
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(secretKeySpec);
return Base64.getEncoder().encodeToString(mac.doFinal(textToHash.getBytes()));
} catch(GeneralSecurityException ignored) {
}
return "";
}
private static byte[] hexStringToByteArray(String str) {
int len = str.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16));
}
return data;
}
}
Hmac Util on NodeJS with crypto lib.
export const computeHMAC = (clientId, dateTime, requestPayload, secretKey) => {
const message = `${clientId}${dateTime}${JSON.stringify(requestPayload).replaceAll(":", ": ").replaceAll(",", ", ")}`;
const keyBuffer = Buffer.from(secretKey, 'hex');
const hmac = crypto.createHmac('sha512', keyBuffer);
return hmac.update(message, 'utf8').digest('base64');
};
Last updated
Was this helpful?