实现代码:
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
|
import java.security.NoSuchAlgorithmException; public class MD5HashUtil { private MessageDigest md = null ; private static MD5HashUtil md5 = null ; private static final char [] hexChars ={ '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' }; /** * Constructor is private so you must use the getInstance method */ private MD5HashUtil() throws NoSuchAlgorithmException { md = MessageDigest.getInstance( "MD5" ); } /** * This returns the singleton instance */ public static MD5HashUtil getInstance() throws NoSuchAlgorithmException { if (md5 == null ) { md5 = new MD5HashUtil(); } return (md5); } public static String hashCode(String dataToHash) throws NoSuchAlgorithmException{ return getInstance().hashData(dataToHash.getBytes()); } public static String hashCode( byte [] dataToHash) throws NoSuchAlgorithmException{ return getInstance().hashData(dataToHash); } public String hashData( byte [] dataToHash) { return hexStringFromBytes((calculateHash(dataToHash))).toLowerCase(); } private byte [] calculateHash( byte [] dataToHash) { md.update(dataToHash, 0 , dataToHash.length); return (md.digest()); } public String hexStringFromBytes( byte [] b) { String hex = "" ; int msb; int lsb = 0 ; int i; // MSB maps to idx 0 for (i = 0 ; i < b.length; i++) { msb = (( int )b[i] & 0x000000FF ) / 16 ; lsb = (( int )b[i] & 0x000000FF ) % 16 ; hex = hex + hexChars[msb] + hexChars[lsb]; } return (hex); } public static void main(String args[]) throws NoSuchAlgorithmException { String string = "my name is zhangli" ; System.out.println(string); System.out.println(hashCode(string)); } } |
如上代码为java语言实现md5加密算法,输出为加密后的密文!
通常将加密后的密文保存在数据库中,如果需要比较只比较他们的用md5加密过后的密文。
同时,md5加密算法是不可逆的,破解的难度很高。
以上就是java MD5加密算法的实例详解,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/fzhlee/article/details/5724530