根据 rfc2202 在 java 中实现 hmac-sha1

Implementation of hmac-sha1 in java according to rfc2202

我正在寻找在 java 中实现 hmac-sha1 的解决方案,这将给我与 rfc2202 文档中描述的相同的输出。 https://www.rfc-editor.org/rfc/rfc2202.html(3. HMAC-SHA-1 测试用例)

我试着写了一些代码,但我离解决方案还很远。最后,我在这里找到了函数:,它在 rfc2202 的测试用例 2 中对我有用,其中 key="Jefe" 和 data="what do ya want for nothing?"我需要更多的输入作为字节数组,所以我改变了它如下所示,但它没有给我正确的摘要。那么我必须做些什么才能使这段代码工作?我想它与字节数组有关,但我可能是 java 的新手,没有任何想法。

这就是我为此函数提供输入的方式(来自 rfc2202 的测试用例 3):

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));

函数代码:

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;
}

测试用例3的密钥错误,应该是:

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