我在单元测试中包含以下内容,以试图弄清楚为什么我的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");
}
这是我在所有情况下都从类路径中读取的图像:
最佳答案
解
我需要先关闭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());
显然,
.digest()
也使其正常运行。关于java - DigestOutputStream没有报告正确的摘要值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25277193/