I'm trying to send requests to API. Api docs provide examples for salt and sign that should be present in request body. PHP example:
$sign_key = 'testString';
$salt = sha1('testKey');
$sign = hash_hmac('sha512', $salt, $sign_key);
My java code is:
String salt = DigestUtils.sha1Hex("testKey");
SecretKeySpec secretKeySpec = new SecretKeySpec(salt.getBytes(StandardCharsets.UTF_8),
"HmacSHA512");
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(secretKeySpec);
String sign = Hex.encodeHexString(mac.doFinal("testString".getBytes(StandardCharsets.UTF_8)));
Salt calculated on php and java matches, but sign differ.
I've checked some posts like following:
Java HmacSHA512
php base64_encode hash_hmac and java gives different results
Compute HMAC-SHA512 with secret key in java
Yet nothing seems to work. I'm pretty confused about this, and would be glad if anybody could explain to me, what am i missing.
sha1Hex("testKey")produces a hex-encoded string representing the bytes, whereas PHPsha1('testKey')produces the actual bytes themselves. The solution would be don't use sha1Hex, instead in Java computebyte [] salt = sha1("testKey").sha1()returns the hex-encoded value, sosha1Hex("testKey")does in fact produce the same output in Java. The problem is simply that you have the arguments reversed. If you instead computehash_hmac('sha512', $sign_key, $salt);you get the same output as Java. Or maybe you meant to reverse the arguments on the Java side? The use of a variable called salt involving a string calledtestKeyand a variable called signKey involving a string calledtestStringmake it impossible to guess which you intend to be the hmac key and which you intend to be the data.