0

我正在使用来自https://www.rfc-editor.org/rfc/rfc4231的测试向量测试我的 Hmac

但是在测试用例 3 中“使用大于 64 字节的密钥和数据的组合长度进行测试(= SHA-224 和 SHA-256 的块大小)。” 我得到的摘要与正确的摘要不同。

byte[] key = hexify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
byte[] data = hexify("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");
byte[] correct = hexify("773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe");

// Create digest
SecretKey macKey = new SecretKeySpec(key, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(macKey);
byte[] digest = mac.doFinal(data);

知道为什么它们会变得不同吗?我错过了什么?我对此很陌生。

// Hex encoded
a5418172bb54bf71f3ec28d1c9f34c48da17007eac4d0ca9e2f8ab54b91603e8
773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe
4

1 回答 1

4

我无法重现您的问题。对我来说,以下 SSCCE 可以正常工作:

public static void main(String[] args) throws Exception {
  byte[] key = hexify("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
  byte[] data = hexify("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");
  byte[] correct = hexify("773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe");

  // Create digest
  SecretKey macKey = new SecretKeySpec(key, "HmacSHA256");
  Mac mac = Mac.getInstance("HmacSHA256");
  mac.init(macKey);
  byte[] digest = mac.doFinal(data);
  System.out.println(Arrays.equals(correct, digest));    
}

private static byte[] hexify(String string) {
  return DatatypeConverter.parseHexBinary(string);
}

印刷:true

也许您的显示或比较代码有错误?

于 2013-04-26T08:41:08.917 回答