提交 | 用户 | 时间
|
e57a89
|
1 |
package com.jcdm.common.utils.sign; |
懒 |
2 |
|
|
3 |
import java.nio.charset.StandardCharsets; |
|
4 |
import java.security.MessageDigest; |
|
5 |
import org.slf4j.Logger; |
|
6 |
import org.slf4j.LoggerFactory; |
|
7 |
|
|
8 |
/** |
|
9 |
* Md5加密方法 |
|
10 |
* |
|
11 |
* @author jc |
|
12 |
*/ |
|
13 |
public class Md5Utils |
|
14 |
{ |
|
15 |
private static final Logger log = LoggerFactory.getLogger(Md5Utils.class); |
|
16 |
|
|
17 |
private static byte[] md5(String s) |
|
18 |
{ |
|
19 |
MessageDigest algorithm; |
|
20 |
try |
|
21 |
{ |
|
22 |
algorithm = MessageDigest.getInstance("MD5"); |
|
23 |
algorithm.reset(); |
|
24 |
algorithm.update(s.getBytes("UTF-8")); |
|
25 |
byte[] messageDigest = algorithm.digest(); |
|
26 |
return messageDigest; |
|
27 |
} |
|
28 |
catch (Exception e) |
|
29 |
{ |
|
30 |
log.error("MD5 Error...", e); |
|
31 |
} |
|
32 |
return null; |
|
33 |
} |
|
34 |
|
|
35 |
private static final String toHex(byte hash[]) |
|
36 |
{ |
|
37 |
if (hash == null) |
|
38 |
{ |
|
39 |
return null; |
|
40 |
} |
|
41 |
StringBuffer buf = new StringBuffer(hash.length * 2); |
|
42 |
int i; |
|
43 |
|
|
44 |
for (i = 0; i < hash.length; i++) |
|
45 |
{ |
|
46 |
if ((hash[i] & 0xff) < 0x10) |
|
47 |
{ |
|
48 |
buf.append("0"); |
|
49 |
} |
|
50 |
buf.append(Long.toString(hash[i] & 0xff, 16)); |
|
51 |
} |
|
52 |
return buf.toString(); |
|
53 |
} |
|
54 |
|
|
55 |
public static String hash(String s) |
|
56 |
{ |
|
57 |
try |
|
58 |
{ |
|
59 |
return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); |
|
60 |
} |
|
61 |
catch (Exception e) |
|
62 |
{ |
|
63 |
log.error("not supported charset...{}", e); |
|
64 |
return s; |
|
65 |
} |
|
66 |
} |
|
67 |
} |