Reputation: 51
try (InputStream is = item.getInputStream())
{
final MD5DigestCalculatingInputStream digestStream = new MD5DigestCalculatingInputStream(is);
final byte[] bytes = IOUtils.toByteArray(digestStream);
final String newFileName = Hex.encodeHexString(digestStream.getMd5Digest()) + "."
+ FilenameUtils.getExtension(item.getName());
final String newFileName2 = Hex.encodeHexString(digestStream.getMd5Digest()) + "."
+ FilenameUtils.getExtension(item.getName());
}
So on the above code i get following results:
newFileName = e9f08a9c181551336e58119edd23109b.png
(Correct)
newFileName2 = d41d8cd98f00b204e9800998ecf8427e.png
(Wrong!)
All following results would also be like the newFileName2. It doesn't matter what the correct newFileName will be, the newFileName2 will always be the same value as shown above. I really don't know what cases this issue?
Upvotes: 0
Views: 683
Reputation: 7541
The getMD5Digest method invokes MessageDigest.digest.
The docs for MessageDigest.digest say
The digest is reset after this call is made.
https://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html#digest()
As a result the first name is the MD5 digest of the input stream. The second name is the MD5 of a newly reset digest, which is why it is always the same.
Upvotes: 3
Reputation: 550
My bet is that MD5DigestCalculatingInputStream.getMd5Digest() consumes the stream. Which means that the first call consumes the digest, and subsequent calls return an empty digest, which would then produce always the same wrong result.
Upvotes: 0