Search code examples
javacryptographyhmacsha1

Implementation of hmac-sha1 in java according to rfc2202


I'm looking for solution to make implementation of hmac-sha1 in java, which will give me same output as it is described in rfc2202 document. https://www.rfc-editor.org/rfc/rfc2202.html (3. Test Cases for HMAC-SHA-1)

I tried to write some code, but I was far from solution. Finally I found function here: https://stackoverflow.com/a/8396600 and it worked for me in test case 2 for rfc2202, where key="Jefe" and data="what do ya want for nothing?" I need more to have input as byte arrays so I changed it as it is below, but it doesn't give me correct digests. So what I have to do to make this code work? I suppose it's something with byte arrays, but I'm likely new to java and out of any ideas.

This is how I was giving input to this function (test case 3 from rfc2202):

byte[] key = new byte[20];
Arrays.fill(key, (byte) 10);
byte[] data = new byte[50];
Arrays.fill(data, (byte) 0xdd);
System.out.println(Prf.hmacsha1Digest(data, key));

And code of the function:

public static String hmacsha1Digest(byte[] msg, byte[] keyin) throws InvalidKeyException {
String digest = null;
String algo = "HmacSHA1";

try {
  SecretKeySpec key = new SecretKeySpec(keyin, algo);
  Mac mac = Mac.getInstance(algo);
  mac.init(key);

  byte[] bytes = mac.doFinal(msg);

  StringBuffer hash = new StringBuffer();
  for (int i = 0; i < bytes.length; i++) {
    String hex = Integer.toHexString(0xFF & bytes[i]);
    if (hex.length() == 1) {
      hash.append('0');
    }
    hash.append(hex);
  }
  digest = hash.toString();
} catch (InvalidKeyException e) {
} catch (NoSuchAlgorithmException e) {
}
return digest;
}

Solution

  • The key is wrong for test case 3. It should be:

    byte[] key = new byte[20];
    Arrays.fill(key, (byte) 0xaa);