1 package net.sf.jpkgmk.util;
2
3 import java.io.BufferedInputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.security.MessageDigest;
9 import java.security.NoSuchAlgorithmException;
10 import java.util.zip.CRC32;
11 import java.util.zip.Checksum;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15
16
17
18
19
20
21
22
23 public class ChecksumUtil
24 {
25 private static Log log = LogFactory.getLog(ChecksumUtil.class);
26
27
28 private ChecksumUtil()
29 {
30
31 }
32
33
34
35
36
37
38
39 public static String md5(File data) throws NoSuchAlgorithmException, IOException
40 {
41 InputStream input = new BufferedInputStream(new FileInputStream(data));
42 try {
43 return md5(input);
44 }
45 finally {
46 StreamUtil.tryCloseStream(input);
47 }
48 }
49
50
51
52
53
54
55
56 public static String md5(InputStream data) throws NoSuchAlgorithmException, IOException
57 {
58 MessageDigest digest = MessageDigest.getInstance("MD5");
59 int b=-1;
60 while((b=data.read())!=-1) {
61 digest.update((byte)b);
62 }
63 byte[] hash = digest.digest();
64
65 return StringUtil.getHexString(hash);
66 }
67
68
69
70
71
72
73
74 public static Long createChecksumCrc32(File file) throws IOException {
75 Checksum checksum = new CRC32();
76 return createChecksum(file, checksum);
77 }
78
79 public static Long createUnixCksum(File file) throws IOException, NoSuchAlgorithmException {
80 return UnixChecksum.createChecksum(file);
81 }
82 public static Long createUnixCksum(byte[] data) throws IOException, NoSuchAlgorithmException {
83 return UnixChecksum.createChecksum(data);
84 }
85
86
87
88
89
90
91
92
93 public static Long createChecksum(File file, Checksum checksum) throws IOException {
94 long millis = System.currentTimeMillis();
95
96 InputStream in = new BufferedInputStream(new FileInputStream(file));
97 try {
98 checksum.reset();
99 int b;
100 while ((b = in.read()) >= 0) {
101 checksum.update(b);
102 }
103 }
104 finally {
105 StreamUtil.tryCloseStream(in);
106 }
107 millis = System.currentTimeMillis() - millis;
108 log.debug("Checksum computed for file '" + file + "'. Second(s): " + (millis/1000L));
109 long checksumVal = checksum.getValue();
110 return Long.valueOf(checksumVal);
111 }
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135 }