1 package endecrypt;
2
3 import java.io.UnsupportedEncodingException;
4 import java.security.MessageDigest;
5 import java.security.NoSuchAlgorithmException;
6
7 /**
8 * 采用MD5加密解密
9 * @author tfq
10 * @datetime 2011-10-13
11 */
12 public class MD5Util {
13
14 /***
15 * MD5加码 生成32位md5码
16 */
17 public static String string2MD5(String inStr){
18 MessageDigest md5 = null;
19 try{
20 md5 = MessageDigest.getInstance("MD5");
21 }catch (Exception e){
22 System.out.println(e.toString());
23 e.printStackTrace();
24 return "";
25 }
26 char[] charArray = inStr.toCharArray();
27 byte[] byteArray = new byte[charArray.length];
28
29 for (int i = 0; i < charArray.length; i++)
30 byteArray[i] = (byte) charArray[i];
31 byte[] md5Bytes = md5.digest(byteArray);
32 StringBuffer hexValue = new StringBuffer();
33 for (int i = 0; i < md5Bytes.length; i++){
34 int val = ((int) md5Bytes[i]) & 0xff;
35 if (val < 16)
36 hexValue.append("0");
37 hexValue.append(Integer.toHexString(val));
38 }
39 return hexValue.toString();
40
41 }
42
43 /**
44 * 加密解密算法 执行一次加密,两次解密
45 */
46 public static String convertMD5(String inStr){
47
48 char[] a = inStr.toCharArray();
49 for (int i = 0; i < a.length; i++){
50 a[i] = (char) (a[i] ^ 't');
51 }
52 String s = new String(a);
53 return s;
54
55 }
56
57 // 测试主函数
58 public static void main(String args[]) {
59 String s = new String("tangfuqiang");
60 System.out.println("原始:" + s);
61 System.out.println("MD5后:" + string2MD5(s));
62 System.out.println("加密的:" + convertMD5(s));
63 System.out.println("解密的:" + convertMD5(convertMD5(s)));
64
65 }
66 }