51

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.

Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
Bee
  • 14,277
  • 6
  • 35
  • 49
  • 2
    Well, how do they differ? Which one matches the test patterns for sha1? A cursory glance at the PHP document shows the "raw_output" options. –  Oct 22 '09 at 21:01
  • Post some test input and output (use hex encoding or base-64 for binary parameters). – erickson Oct 22 '09 at 21:03

7 Answers7

41

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
  • 611
  • 1
  • 8
  • 7
20

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();
}
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
dharan
  • 743
  • 2
  • 10
  • 28
5

This is my implementation :

        String hmac = "";

    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(llave.getBytes(), "HmacSHA1");
    mac.init(secret);
    byte[] digest = mac.doFinal(cadena.getBytes());
    BigInteger hash = new BigInteger(1, digest);
    hmac = hash.toString(16);

    if (hmac.length() % 2 != 0) {
        hmac = "0" + hmac;
    }

    return hmac;
atomsfat
  • 2,863
  • 6
  • 34
  • 36
3

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,796
  • 2
  • 16
  • 13
3

My implementation for HmacMD5 - just change algorithm to HmacSHA1:

SecretKeySpec keySpec = new SecretKeySpec("secretkey".getBytes(), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
byte[] hashBytes = mac.doFinal("text2crypt".getBytes());
return Hex.encodeHexString(hashBytes);
Krizko
  • 31
  • 2
3

This way I could get the exact same string as I was getting with hash_hmac in php

String result;

try {
        String data = "mydata";
        String key = "myKey";
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        result = new String(hexBytes, "ISO-8859-1");
        out.println("MAC : " + result);
}
catch (Exception e) {

}
Akhil
  • 2,602
  • 23
  • 36
1

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
  • 109,619
  • 77
  • 317
  • 330
  • Of course, using new StringBuilder(digest.length * 2), a for/next loop and append(String.format("%02X"), digest[i] & 0xFF) is less memory intensive and possibly a bit more readable. – Maarten Bodewes Nov 21 '11 at 22:10
  • the if statement needs to be a while loop. it won't work for the multiple leading zeroes case. – slushi Jun 06 '13 at 14:37