package org.simantics.fastlz; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author Tuukka Lehtonen */ public final class ChecksumUtil { public static byte[] computeSum(byte[] in) { if (in == null) throw new IllegalArgumentException("Input cannot be null!"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(in, 0, in.length); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new Error("MD5 digest must be supported by JVM"); } } public 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(File f) throws IOException { InputStream in = null; try { in = new FileInputStream(f); return computeSum(in); } finally { if (in != null) in.close(); } } public static byte[] computeSum(URL url) throws IOException { InputStream in = null; try { in = url.openStream(); return computeSum(in); } finally { if (in != null) in.close(); } } }