title: Android MD5 hash from contentresolver inputstream
body: <p>I'm trying to upload a file from my android app to my server, and to be sure it is done correctly I would like to add the MD5 hash. The file to be uploaded is referenced by a content:// Uri. I use the below code to calculate the MD5 hash on my android device, and a slightly different code on my server (see comment in code). Now the problem is that these 2 don't give the same result. I've used some third-party software and the MD5 hash on my server is actually correct. How do I solve this?</p>
  
  <pre><code>public static String calculateMD5(Context context, Uri fileUri) {
      MessageDigest digest;
      try {
          digest = MessageDigest.getInstance("MD5");
      } catch (NoSuchAlgorithmException e) {
          Log.e(LOG_TAG, "Exception while getting digest", e);
          return null;
      }
  
      InputStream is;
      try {
          is = context.getContentResolver().openInputStream(fileUri);
          // is = new FileInputStream("some_file_location");
      } catch (FileNotFoundException e) {
          Log.e(LOG_TAG, "Exception while getting FileInputStream", e);
          return null;
      }
  
      byte[] buffer = new byte[8192];
      int read;
      try {
          while ((read = is.read(buffer)) &gt; 0) {
              digest.update(buffer, 0, read);
          }
          byte[] md5sum = digest.digest();
  
          // Create Hex String
          StringBuilder hexString = new StringBuilder();
          for (byte aMessageDigest : md5sum) {
              String h = Integer.toHexString(0xFF &amp; aMessageDigest);
              while (h.length() &lt; 2)
                  h = "0" + h;
              hexString.append(h);
          }
          return hexString.toString();
      } catch (IOException e) {
          throw new RuntimeException("Unable to process file for MD5", e);
      } finally {
          try {
              if (is != null) {
                  is.close();
              }
          } catch (IOException e) {
              Log.e(LOG_TAG, "Exception on closing MD5 input stream", e);
          }
      }
  }
  </code></pre>