tags:

views:

1323

answers:

4

I'm looking for a java equivalent to this php call:

hash_hmac('sha1', "test", "secret")

I tried this, using java.crypto.Mac, but the two do not agree:

String mykey = "secret";
String test = "test";
try {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(mykey.getBytes(),"HmacSHA1");
    mac.init(secret);
    byte[] digest = mac.doFinal(test.getBytes());
    String enc = new String(digest);
    System.out.println(enc);  
} catch (Exception e) {
    System.out.println(e.getMessage());
}

The outputs with key = "secret" and test = "test" do not seem to match.

+1  A: 

Seems to me that PHP uses HEX notation for the bytes that Java produces (1a = 26) - but I didn't check the whole expression.

What happens if you run the byte array through the method on this page?

Hans Doggen
+1  A: 

Haven't tested it, but try this:

  BigInteger hash = new BigInteger(1, digest);
  String enc = hash.toString(16);
  if ((enc.length() % 2) != 0) {
   enc = "0" + enc;
  }

This is snapshot from my method that makes java's md5 and sha1 match php.

serg
+4  A: 

In fact they do agree.
As Hans Doggen already noted PHP outputs the message digest using hexadecimal notation unless you set the raw output parameter to true.
If you want to use the same notation in Java you can use something like

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

to format the output accordingly.

Dirk D
A: 

Could someone please post the complete code snippet?

Chris
http://stackoverflow.com/questions/3483582/how-to-create-oauth-hmac-sha1-signature-on-gae-j/3485422#3485422
Jaroslav Záruba