0

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.

judge73
  • 1
  • 1
  • Title implies mismatch of hash generated in two PHP instances but body indicates it is PHP and Java. Clean up the title? – vsfDawg Aug 12 '21 at 13:19
  • renamed the title – judge73 Aug 12 '21 at 13:52
  • I assume Java `sha1Hex("testKey")` produces a hex-encoded string representing the bytes, whereas PHP `sha1('testKey')` produces the actual bytes themselves. The solution would be don't use sha1Hex, instead in Java compute `byte [] salt = sha1("testKey")`. – President James K. Polk Aug 13 '21 at 01:14
  • sha1Hex is used for salt, and salt are equal on php and java (both as hexString and byte array). The issue is with mac behaviour itself. – judge73 Aug 13 '21 at 08:53
  • I see that php `sha1()` returns the hex-encoded value, so `sha1Hex("testKey")` does in fact produce the same output in Java. The problem is simply that you have the arguments reversed. If you instead compute `hash_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 called `testKey` and a variable called signKey involving a string called `testString` make it impossible to guess which you intend to be the hmac key and which you intend to be the data. – President James K. Polk Aug 14 '21 at 12:58
  • Oh god. Now i feel dumb. Indeed i reversed args in java and hashes match each other. Thanks! – judge73 Aug 15 '21 at 15:44

0 Answers0