Question

I am trying to match the md5sum of a downloaded file from server. Processing will be continued only if sums match.

try {
      MessageDigest digest = MessageDigest.getInstance("MD5");
      File f = new File(fileName);
      InputStream is = new FileInputStream(f);              
      byte[] buffer = new byte[8192];
      int read = 0;
      while( (read = is.read(buffer)) > 0) {
          digest.update(buffer, 0, read);
      } 
      is.close();
      byte[] md5sum = digest.digest();
      BigInteger bigInt = new BigInteger(1, md5sum);
      output = bigInt.toString(16);
      System.out.println("MD5: " + output);
  } catch(IOException e) {
      throw new RuntimeException("Unable to process file for MD5", e);
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  }

Above code doesn't provide the md5sum properly for some files every time.

When i go to console and check md5sum <filename> md5sum is same as that in server. But when same is calculated from code it is yielding a different result.

vimdiff of downloaded file is not providing any diff.. The files are proper after download.

I am unable to see a problem in above code.

I am trying to change the buffer size. But no luck, So i am guessing that it is not because of the buffer size etc.

 byte[] buffer = new byte[8192];

Regards
Dheeraj Joshi

Was it helpful?

Solution

BigInteger.toString method will escape the leading 0's as they are not important.

BigInteger.toString method is deleting leading 0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top