]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.fastlz/testcases/org/simantics/fastlz/ChecksumUtil.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.fastlz / testcases / org / simantics / fastlz / ChecksumUtil.java
1 package org.simantics.fastlz;\r
2 \r
3 import java.io.File;\r
4 import java.io.FileInputStream;\r
5 import java.io.IOException;\r
6 import java.io.InputStream;\r
7 import java.net.URL;\r
8 import java.security.MessageDigest;\r
9 import java.security.NoSuchAlgorithmException;\r
10 \r
11 /**\r
12  * @author Tuukka Lehtonen\r
13  */\r
14 public final class ChecksumUtil {\r
15 \r
16     public static byte[] computeSum(byte[] in) {\r
17         if (in == null)\r
18             throw new IllegalArgumentException("Input cannot be null!");\r
19         try {\r
20             MessageDigest md = MessageDigest.getInstance("MD5");\r
21             md.update(in, 0, in.length);\r
22             return md.digest();\r
23         } catch (NoSuchAlgorithmException e) {\r
24             throw new Error("MD5 digest must be supported by JVM");\r
25         }\r
26     }\r
27 \r
28     public static byte[] computeSum(InputStream in) throws IOException {\r
29         if (in == null)\r
30             throw new IllegalArgumentException("Input cannot be null!");\r
31 \r
32         MessageDigest md;\r
33         try {\r
34             md = MessageDigest.getInstance("MD5");\r
35         } catch (NoSuchAlgorithmException e) {\r
36             throw new Error("MD5 digest must be supported by JVM");\r
37         }\r
38         byte[] data = new byte[64 * 1024];\r
39 \r
40         while (true) {\r
41             int read = in.read(data);\r
42             if (read == -1) {\r
43                 return md.digest();\r
44             }\r
45             md.update(data, 0, read);\r
46         }\r
47     }\r
48 \r
49     public static byte[] computeSum(File f) throws IOException {\r
50         InputStream in = null;\r
51         try {\r
52             in = new FileInputStream(f);\r
53             return computeSum(in);\r
54         } finally {\r
55             if (in != null)\r
56                 in.close();\r
57         }\r
58     }\r
59 \r
60     public static byte[] computeSum(URL url) throws IOException {\r
61         InputStream in = null;\r
62         try {\r
63             in = url.openStream();\r
64             return computeSum(in);\r
65         } finally {\r
66             if (in != null)\r
67                 in.close();\r
68         }\r
69     }\r
70 \r
71 }\r