2

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;
}
2
  • I have a wide variety of test vectors for PBKDF2-HMAC-... at my github repository: github.com/Anti-weakpasswords/PBKDF2-Test-Vectors if you'd like to validate your algorithm against them. Commented Feb 8, 2016 at 6:03
  • How can I use salt here Commented Oct 21, 2017 at 7:24

1 Answer 1

2

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

byte[] key = new byte[20];
Arrays.fill(key, (byte) 0xaa);
Sign up to request clarification or add additional context in comments.

1 Comment

Hahaha, oh man. It made my day. Maybe I'm overworked a little bit xP Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.