MD5.java
2.43 KB
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
package com.server.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
/**
* MD5
*/
public final class MD5 {
private MD5() {
}
private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static String md5(String txt) {
try {
return md5(txt.getBytes("UTF-8"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String md5(String... txt) {
return md5(StrUtils.joinString(",", txt));
}
public static String md5(byte[] data) {
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
byte[] bytes = data;
mdTemp.update(bytes);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param file
* @return
* @throws IOException
*/
public static String fileMd5(File file) throws Exception {
try (FileInputStream in = new FileInputStream(file)) {
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileChannel fChannel = in.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
for (int count = fChannel.read(buffer); count != -1; count = fChannel.read(buffer)) {
buffer.flip();
md5.update(buffer);
if (!buffer.hasRemaining()) {
buffer.clear();
}
}
//
byte[] md = md5.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception ex) {
throw ex;
}
}
}