YiFeng
YiFeng

Reputation: 387

The real difference between the MessageDigest`s two update methods?

Example one:

FileInputStream fis = new FileInputStream(path);
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
  digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return  bigInt.toString(16);

Example two:

FileInputStream fis = new FileInputStream(path);
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
while ((fis.read(buffer)) != -1) {
  digest.update(buffer);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return  bigInt.toString(16);

In the above two examples, I use two different update methods. When I pass a same file path, the two operations return two different results. Is the update method append mode? Why I got different results?

Upvotes: 0

Views: 115

Answers (1)

Henry
Henry

Reputation: 43738

The first one works, the second doesn't. The read does not necessarily fill the full buffer, but in the second example you always send all bytes to the digest.

Upvotes: 3

Related Questions