From 640926110be6cbc56649e8a6fb3c252659774ce5 Mon Sep 17 00:00:00 2001 From: Mathis Chenuet Date: Thu, 5 Mar 2015 20:27:13 +0000 Subject: [PATCH] Cleanup Utils.md5 method by using DatatypeConverter and DigestInputStream classes --- src/com/sheepit/client/Utils.java | 59 +++++++------------------------ 1 file changed, 13 insertions(+), 46 deletions(-) diff --git a/src/com/sheepit/client/Utils.java b/src/com/sheepit/client/Utils.java index de8c5a8..d778fc6 100644 --- a/src/com/sheepit/client/Utils.java +++ b/src/com/sheepit/client/Utils.java @@ -21,11 +21,12 @@ package com.sheepit.client; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; @@ -36,6 +37,8 @@ import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import javax.xml.bind.DatatypeConverter; + import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -102,54 +105,18 @@ public class Utils { } public static String md5(String path_of_file_) { - MessageDigest digest; try { - digest = MessageDigest.getInstance("MD5"); + MessageDigest md = MessageDigest.getInstance("MD5"); + InputStream is = Files.newInputStream(Paths.get(path_of_file_)); + DigestInputStream dis = new DigestInputStream(is, md); + byte[] buffer = new byte[8192]; + while (dis.read(buffer) > 0) + ; // process the entire file + return DatatypeConverter.printHexBinary(md.digest()).toLowerCase(); } - catch (NoSuchAlgorithmException e1) { - e1.printStackTrace(); + catch (NoSuchAlgorithmException | IOException e) { return ""; } - File f = new File(path_of_file_); - InputStream is; - try { - is = new FileInputStream(f); - } - catch (FileNotFoundException e1) { - e1.printStackTrace(); - return ""; - } - byte[] buffer = new byte[8192]; - int read = 0; - try { - while ((read = is.read(buffer)) > 0) { - digest.update(buffer, 0, read); - } - byte[] md5sum = digest.digest(); - BigInteger bigInt = new BigInteger(1, md5sum); - - String output = bigInt.toString(16); - - // fill with "0" because bigInt.toString does not add 0 at the beginning of the result - int zero_to_add = 32 - output.length(); - for (int i = 0; i < zero_to_add; i++) - output = "0" + output; - - return output; - } - catch (IOException e) { - e.printStackTrace(); - } - finally { - try { - is.close(); - } - catch (IOException e) { - e.printStackTrace(); - //throw new RuntimeException("Unable to close input stream for MD5 calculation", e); - } - } - return ""; } public static double lastModificationTime(File directory_) {