我在单元测试中有以下内容,试图弄清楚为什么我的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
为了完整起见,这里是我为每个案例阅读的内容:
private InputStream getInputStream()
{
return Thread.currentThread().getContextClassLoader().getResourceAsStream("Al_Bundy_Shoot_Me_$12.jpg");
}
以下是我在所有情况下从类路径中读取的图像:
答案 0 :(得分:1)
在尝试关闭DigestOutputStream
之前,我需要关闭.digest()
。
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()
也使其行为正常。