Skip to content

Commit 78e6634

Browse files
committed
Add DigestUtils
1 parent 7013abb commit 78e6634

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package cn.trinea.android.common.util;
2+
3+
import java.security.MessageDigest;
4+
5+
/**
6+
* DigestUtils
7+
*
8+
* @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2014-03-20
9+
*/
10+
public class DigestUtils {
11+
12+
/**
13+
* Used to build output as Hex
14+
*/
15+
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
16+
'e', 'f' };
17+
18+
/**
19+
* encode By MD5
20+
*
21+
* @param str
22+
* @return String
23+
*/
24+
public static String md5(String str) {
25+
if (str == null) {
26+
return null;
27+
}
28+
try {
29+
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
30+
messageDigest.update(str.getBytes());
31+
return new String(encodeHex(messageDigest.digest()));
32+
} catch (Exception e) {
33+
throw new RuntimeException(e);
34+
}
35+
}
36+
37+
/**
38+
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
39+
* The returned array will be double the length of the passed array, as it takes two characters to represent any
40+
* given byte.
41+
*
42+
* @param data a byte[] to convert to Hex characters
43+
* @return A char[] containing hexadecimal characters
44+
*/
45+
protected static char[] encodeHex(final byte[] data) {
46+
final int l = data.length;
47+
final char[] out = new char[l << 1];
48+
// two characters form the hex value.
49+
for (int i = 0, j = 0; i < l; i++) {
50+
out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
51+
out[j++] = DIGITS_LOWER[0x0F & data[i]];
52+
}
53+
return out;
54+
}
55+
}

0 commit comments

Comments
 (0)