0

I need to get string's hash in Java, same as for PHP's hash_hmac.

Here's my PHP sample:

$secret_key = 'foo';
$sig_str = 'bar';
$hash = hash_hmac('md5', $sig_str, $secret_key); 

And that's what I found for Java:

SecretKeySpec keySpec = new SecretKeySpec("foo".getBytes(), "HmacMD5");
Mac mac = Mac.getInstance(keySpec.getAlgorithm());
mac.init(keySpec);
String result = new BASE64Encoder().encode(mac.doFinal("bar".getBytes()));

But results are different. What am I missing?

uncle Lem
  • 4,954
  • 8
  • 33
  • 53

1 Answers1

0

Found solution here: java equivalent to php's hmac-SHA1

The problem was in BASE64Encoder. Use

for (byte b : digest) {
    System.out.format("%02x", b);
}
System.out.println();

or

new BigInteger(digest).toString(16);

instead.

Community
  • 1
  • 1
uncle Lem
  • 4,954
  • 8
  • 33
  • 53