提交 | 用户 | age
|
5c5945
|
1 |
package com.hx.util; |
E |
2 |
|
|
3 |
import java.security.MessageDigest; |
|
4 |
|
|
5 |
public class MD5Util { |
|
6 |
|
|
7 |
private static String byteArrayToHexString(byte b[]) { |
|
8 |
StringBuffer resultSb = new StringBuffer(); |
|
9 |
for (int i = 0; i < b.length; i++) |
|
10 |
resultSb.append(byteToHexString(b[i])); |
|
11 |
|
|
12 |
return resultSb.toString(); |
|
13 |
} |
|
14 |
|
|
15 |
private static String byteToHexString(byte b) { |
|
16 |
int n = b; |
|
17 |
if (n < 0) |
|
18 |
n += 256; |
|
19 |
int d1 = n / 16; |
|
20 |
int d2 = n % 16; |
|
21 |
return hexDigits[d1] + hexDigits[d2]; |
|
22 |
} |
|
23 |
|
|
24 |
/** |
|
25 |
* @param origin 加密信息 |
|
26 |
* @param charsetname 加密信息的字符串名称(可以为空) |
|
27 |
* @return |
|
28 |
*/ |
|
29 |
public static String MD5Encode(String origin, String charsetname) { |
|
30 |
String resultString = null; |
|
31 |
try { |
|
32 |
resultString = new String(origin); |
|
33 |
MessageDigest md = MessageDigest.getInstance("MD5"); |
|
34 |
if (charsetname == null || "".equals(charsetname)) |
|
35 |
resultString = byteArrayToHexString(md.digest(resultString |
|
36 |
.getBytes())); |
|
37 |
else |
|
38 |
resultString = byteArrayToHexString(md.digest(resultString |
|
39 |
.getBytes(charsetname))); |
|
40 |
} catch (Exception exception) { |
|
41 |
} |
|
42 |
return resultString; |
|
43 |
} |
|
44 |
|
|
45 |
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", |
|
46 |
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; |
|
47 |
|
|
48 |
} |