1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package cn.chnmuseum.party.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5Utils {
private static final Logger logger = LoggerFactory.getLogger(Md5Utils.class);
protected static char[] hexDegists = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
protected static MessageDigest md5 = null;
static {
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
logger.info(Md5Utils.class.getName() + "初始化失败,MessageDigest不支持md5!");
nsae.printStackTrace();
}
}
/**
* 获取md5校验码
*
* @param inputStream
* @return
* @throws IOException
*/
public static String getFileMD5String(java.io.InputStream inputStream) throws IOException {
// 每次读取1024字节
byte[] buffer = new byte[1024];
int readNum = 0;
while ((readNum = inputStream.read(buffer)) > 0) {
md5.update(buffer, 0, readNum);
}
inputStream.close();
return bufferToHex(md5.digest());
}
/**
* 更新需要校验的文件输入流
*
* @param bs
* @return
* @throws IOException
*/
public static void updateFileMD5String(byte[] bs, int readNum) {
// 每次读取bs字节,更新MD5输入流
md5.update(bs, 0, readNum);
}
/**
* 返回md5校验码
*
* @return
* @throws IOException
*/
public static String getFileMD5String() {
return bufferToHex(md5.digest());
}
private static String bufferToHex(byte[] bytes) {
return bufferToHex(bytes, 0, bytes.length);
}
private static String bufferToHex(byte[] bytes, int m, int n) {
StringBuffer stringBuffer = new StringBuffer(n * 2);
int k = m + n;
for (int i = m; i < k; i++) {
appendHexPair(bytes[i], stringBuffer);
}
return stringBuffer.toString();
}
private static void appendHexPair(byte bt, StringBuffer stringBuffer) {
// 取字节中高四位进行转换
char ch0 = hexDegists[(bt & 0xf0) >> 4];
// 取字节中低四位进行转换
char ch1 = hexDegists[(bt & 0xf)];
stringBuffer.append(ch0);
stringBuffer.append(ch1);
}
}