Why do these two sources calculate different sha-1 sums

The following snippets are supposed to compute the sha-1 sum. But for the same file, they calculate different sha-1 sums.

//snippet1
byte[] byteArr = new byte[(int) uploadedFile.getLength()];
try {
 stream = new BufferedInputStream(uploadedFile.getInputStream());
 stream.read(byteArr);
 stream.close(); 
} catch (IOException e) {
 e.printStackTrace();
}
md = MessageDigest.getInstance("SHA-1"); 
byte[] sha1hash = new byte[40];
md.update(byteArr, 0, byteArr.length);
sha1hash = md.digest();

//snippet2
md = MessageDigest.getInstance("SHA-1");
InputStream is = uploadedFile.getInputStream();
try {
 is = new DigestInputStream(is, md);
} finally {
 try {
  is.close();
 } catch (IOException e) {
  e.printStackTrace();
 }
}
sha1hash = md.digest();

      

Can you explain why?

+2


source to share


2 answers


Both of your snippets are errors:



  • The first snapshot reads some (effectively random) number of bytes from the file and is in no way guaranteed to read the entire file (read JavaDocread()

    ).

  • The second snapshot does not read anything from the InputStream and therefore returns the SHA-1 of an empty stream (0 bytes read).

+12


source


You have an error here:

 stream = new BufferedInputStream(uploadedFile.getInputStream());
 stream.read(byteArr);
 stream.close(); 

      



The method read()

does not populate an auto-filled array - it will read an arbitrary number of bytes and return that number. You must loop and add the returned byte before filling the array.

Almost everyone gets it wrong the first time, but this is one of the reasons a stream based method is better (the other is for large files, you definitely don't want to keep them all in memory).

+3


source







All Articles