Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java equivalent to php's hmac-SHA1

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.

like image 714
Bee Avatar asked Oct 22 '09 20:10

Bee


2 Answers

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.

like image 93
Dirk D Avatar answered Oct 10 '22 05:10

Dirk D


You can try this in Java:

private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException {      SecretKey secretKey = null;      byte[] keyBytes = keyString.getBytes();     secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");      Mac mac = Mac.getInstance("HmacSHA1");      mac.init(secretKey);      byte[] text = baseString.getBytes();      return new String(Base64.encodeBase64(mac.doFinal(text))).trim(); } 
like image 45
dharan Avatar answered Oct 10 '22 05:10

dharan