I'm trying to setup a secure hash key in java (android). It's not getting the same result as that of php side (which I use as a reference and it works).
I've gone through many similar questions, but (only one, I tried it but doesn't work) none doesn't solved it clearly. Here's the codes I've tested.
// php code
$secureHash = 'ABCD';
$secret = '123AE45F';
echo '<br> using pack--';
echo hash_hmac('sha256', $secureHash, pack('H*', $secret));
echo '<br> without using pack--';
echo hash_hmac('sha256', $secureHash, $secret, false);
result with pack : f7a009f2c3e654fa48296917ab6372ecb7aa2a24c43fccb70af743f66b6dba55
result without pack : fc602f0f6faf2072be9c0b995ee3d603f61414c4beb027b678c90946db6903a2
// Java code
private String getHashCode(String message, String secretKey) {
Mac mac;
String result = null;
try {
byte[] byteKey = secretKey.getBytes(StandardCharsets.UTF_8);
final String hmacSHA256 = "HmacSHA256";
mac = Mac.getInstance(hmacSHA256);
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), hmacSHA256);
sha256HMAC.init(keySpec);
byte[] mac_data = sha256HMAC.doFinal(message.getBytes(StandardCharsets.UTF_8));
result = bytesToHex(mac_data);
System.out.println("getHashCode: result " + result);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return result;
}
In the Java code I'm getting the output as
fc602f0f6faf2072be9c0b995ee3d603f61414c4beb027b678c90946db6903a2
same as php code without pack. How can I achieve the same output as PHP, ie using the pack('H*', $secret)
in Java code ?