gpt4 book ai didi

java - DigestOutputStream 未报告正确的摘要值

转载 作者:太空宇宙 更新时间:2023-11-04 06:36:44 25 4
gpt4 key购买 nike

我在单元测试中有以下内容,试图找出为什么我的 DigestOutputStream未计算测试的正确摘要 .jpg我在类路径中。

assertArrayEquals()通过但最后assertEquals()失败并产生不同的结果。

// the .jpg is 32394 bytes

final MessageDigest md5 = MessageDigest.getInstance("md5");
md5.update(ByteStreams.toByteArray(getInputStream()));
final String h0 = DatatypeConverter.printHexBinary(md5.digest());
System.out.println("MD5 = " + h0); // MD5 = 98BE96C5B9C8D0E41723BBA6E508AADC

// raw MessageDigest from InputStream to ByteArrayOutputStream
final MessageDigest md5a = MessageDigest.getInstance("md5");
final ByteArrayOutputStream baosa = new ByteArrayOutputStream(32394);
ByteStreams.copy(getInputStream(), baosa);
md5a.update(baosa.toByteArray());
final String ha = DatatypeConverter.printHexBinary(md5a.digest());
assertArrayEquals(ByteStreams.toByteArray(getInputStream()),baosa.toByteArray());
assertEquals(h0,ha);

// raw DigestOutputStream to ByteArrayOutputStream
final ByteArrayOutputStream baosb = new ByteArrayOutputStream(32394);
final DigestOutputStream dos = new DigestOutputStream(baosb, MessageDigest.getInstance("md5"));
ByteStreams.copy(getInputStream(), dos);
final String hb = DatatypeConverter.printHexBinary(dos.getMessageDigest().digest());
assertArrayEquals(baosa.toByteArray(), baosb.toByteArray());
assertEquals(h0,hb); // <-- this is where it fails

失败:

MD5 = 98BE96C5B9C8D0E41723BBA6E508AADC

org.junit.ComparisonFailure:
Expected :98BE96C5B9C8D0E41723BBA6E508AADC
Actual :D41D8CD98F00B204E9800998ECF8427E

为什么 DigestOutputStream 没有返回正确的值?

为了完整起见,以下是我正在阅读的每个案例的内容:

private InputStream getInputStream()
{
return Thread.currentThread().getContextClassLoader().getResourceAsStream("Al_Bundy_Shoot_Me_$12.jpg");
}

这是我在所有情况下从类路径读取的图像:

Al_Bundy_Shoot_Me_$12.jpg

最佳答案

解决方案

在尝试获取 .digest() 之前,我需要关闭 DigestOutputStream

final DigestOutputStream dos = new DigestOutputStream(baosb, MessageDigest.getInstance("md5"));
ByteStreams.copy(getInputStream(), dos);
dos.close(); // <-- this fixed the problem!
final String hb = DatatypeConverter.printHexBinary(dos.getMessageDigest().digest());

显然 .flush() 也使其行为正确。

关于java - DigestOutputStream 未报告正确的摘要值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25277193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com