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.

6
  • Title implies mismatch of hash generated in two PHP instances but body indicates it is PHP and Java. Clean up the title? Commented Aug 12, 2021 at 13:19
  • renamed the title Commented Aug 12, 2021 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"). Commented Aug 13, 2021 at 1: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. Commented Aug 13, 2021 at 8: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. Commented Aug 14, 2021 at 12:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.