MD5加密-JAVA

 1 package Huang.company;
 2 import java.security.MessageDigest;
 3 import java.security.NoSuchAlgorithmException;
 4 /**
 5 * @author stunet
 6 *
 7 * 采用Java对字符串进行MD5的加密以及验证示例
 8 *
 9 */
10 public class MD5DigestDemo {
11 public static void main(String[] args) {
12 
13 try {
14 // 进行字符串加密
15 String password = "huangyuan";
16 System.out.println("加密前的字符串" +password);
17 System.out.println("加密后字符串:" + MD5DigestDemo.md5Digest(password));
18 // 进行字符串验证
19 String validate = MD5DigestDemo.md5Digest(password);
20 String passwordValidate = password;
21 boolean isSuccess = MD5DigestDemo.isValidate(toBytes(validate),passwordValidate);
22 if (isSuccess)
23 System.out.println("验证成功!");
24 else
25 System.out.println("验证失败!");
26 } catch (NoSuchAlgorithmException e) {
27 e.printStackTrace();
28 }
29 }
30 
31 /**
32 *
33 * @param password
34 * 需要加密的字符串
35 * @return 加密后的字符串
36 * @throws NoSuchAlgorithmException
37 */
38 public static String md5Digest(String password)
39 throws NoSuchAlgorithmException {
40 String temp;
41 MessageDigest alg = MessageDigest.getInstance("MD5");
42 alg.update(password.getBytes());
43 byte[] digest = alg.digest();
44 temp = byte2hex(digest);
45 return temp;
46 }
47 /**
48 *
49 * @param digest
50 * 加密后的字符串
51 * @param password
52 * 验证的字符串
53 * @return 验证是否成功
54 * @throws NoSuchAlgorithmException
55 */
56 public static boolean isValidate(byte[] digest, String password)
57 throws NoSuchAlgorithmException {
58 boolean flag = false;
59 MessageDigest alg = MessageDigest.getInstance("MD5");
60 alg.update(password.getBytes());
61 if (MessageDigest.isEqual(digest, alg.digest()))
62 flag = true;
63 else
64 flag = false;
65 return flag;
66 }
67 /*
68 * 二进制转换为十六进制字符串
69 *
70 * @param b 二进制数组 @return 十六进制字符串
71 */
72 private static String byte2hex(byte[] bytes) {
73 String hs = "";
74 String stmp = "";
75 for (int i = 0; i < bytes.length; i++) {
76 stmp = (java.lang.Integer.toHexString(bytes[i] & 0XFF));
77 if (stmp.length() == 1)
78 hs = hs + "0" + stmp;
79 else
80 hs = hs + stmp;
81 }
82 return hs.toUpperCase();
83 }
84 /*
85 * 把字符串转换成byte[]
86 *
87 * @param hex 要转换的字符串 @return 转换后的byte[]
88 */
89 private static byte[] toBytes(String hex) {
90 byte[] bytes = new byte[16];
91 for (int i = 0, j = 0; i < hex.length(); i = i + 2, j++) {
92 bytes[j] = Integer.valueOf(hex.substring(i, i + 2), 16).byteValue();
93 }
94 return bytes;
95 }
96 }
转载

 

posted on 2014-12-31 11:03  随风浪子的博客  阅读(429)  评论(0编辑  收藏  举报

导航