package net.jpountz.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author Tuukka Lehtonen */ public final class ChecksumUtil { private static byte[] computeSum(InputStream in) throws IOException { if (in == null) throw new IllegalArgumentException("Input cannot be null!"); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new Error("MD5 digest must be supported by JVM"); } byte[] data = new byte[64 * 1024]; while (true) { int read = in.read(data); if (read == -1) { return md.digest(); } md.update(data, 0, read); } } public static byte[] computeSum(Path p) throws IOException { try (InputStream in = Files.newInputStream(p)) { return computeSum(in); } } public static byte[] computeSum(URL url) throws IOException { try (InputStream in = url.openStream()) { return computeSum(in); } } }