Calculate HMAC Hash in Java

April 21, 2011

I needed to calculate a HMAC hash in Java, getting the same format as php's hash_hmac() function in return.

This can be done using the following Java function:

private static String buildHmacSignature(String pKey, String pStringToSign)
{
  String lSignature = "None";
  try
  {
    Mac lMac = Mac.getInstance("HmacSHA1");
    SecretKeySpec lSecret = new SecretKeySpec(pKey.getBytes(), "HmacSHA1");
    lMac.init(lSecret);

    byte[] lDigest = lMac.doFinal(pStringToSign.getBytes());
    BigInteger lHash = new BigInteger(1, lDigest);
    lSignature = lHash.toString(16);
    if ((lSignature.length() % 2) != 0) {
      lSignature = "0" + lSignature;
    }
  }
  catch (NoSuchAlgorithmException lEx)
  {
    throw new RuntimeException("Problems calculating HMAC", lEx);
  }
  catch (InvalidKeyException lEx)
  {
    throw new RuntimeException("Problems calculating HMAC", lEx);
  }

  return lSignature;
}

Tags: hmac hash java