-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMD5Demo.java
More file actions
50 lines (44 loc) · 1.32 KB
/
Copy pathMD5Demo.java
File metadata and controls
50 lines (44 loc) · 1.32 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
package com.yale.test.ps.md5;
import java.security.MessageDigest;
/*
* 一文让你轻松了解 JAVA 开发中的四种加密方法
* https://zhuanlan.zhihu.com/p/93860175
* 芋道源码
*/
public class MD5Demo {
private static final String[] hexDigIts = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (null == charsetname || "".equals(charsetname)) {
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
} else {
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
} catch (Exception e) {
e.printStackTrace();
}
return resultString;
}
public static String byteArrayToHexString(byte[] b) {
StringBuilder result = new StringBuilder();
for (int i=0; i<b.length; i++) {
result.append(byteToHexString(b[i]));
}
return result.toString();
}
public static String byteToHexString(byte b) {
int n = b;
if (n <0) {
n +=256;
}
int d1 = n / 126;
int d2 = n % 16;
return hexDigIts[d1] + hexDigIts[d2];
}
public static void main(String[] args) {
System.out.println(MD5Demo.MD5Encode("ABC", "UTF-8"));
}
}