View Javadoc
1   package gboat2.web.util;
2   
3   import java.io.UnsupportedEncodingException;
4   import java.security.MessageDigest;
5   import java.security.NoSuchAlgorithmException;
6   
7   public class EncryptUtil {
8   
9   	// md5加密
10  	public static String md5(String inputText) {
11  		return encrypt(inputText, "md5");
12  	}
13  
14  	// sha加密
15  	public static String sha(String inputText) {
16  		return encrypt(inputText, "sha-1");
17  	}
18  
19  	/**
20  	 * md5或者sha-1加密
21  	 * 
22  	 * @param inputText
23  	 *            要加密的内容
24  	 * @param algorithmName
25  	 *            加密算法名称:md5或者sha-1,不区分大小写
26  	 * @return
27  	 */
28  	private static String encrypt(String inputText, String algorithmName) {
29  		if (inputText == null || "".equals(inputText.trim())) {
30  			throw new IllegalArgumentException("请输入要加密的内容");
31  		}
32  		if (algorithmName == null || "".equals(algorithmName.trim())) {
33  			algorithmName = "md5";
34  		}
35  		String encryptText = null;
36  		try {
37  			MessageDigest m = MessageDigest.getInstance(algorithmName);
38  			m.update(inputText.getBytes("UTF8"));
39  			byte s[] = m.digest();
40  			// m.digest(inputText.getBytes("UTF8"));
41  			return hex(s);
42  		} catch (NoSuchAlgorithmException e) {
43  			e.printStackTrace();
44  		} catch (UnsupportedEncodingException e) {
45  			e.printStackTrace();
46  		}
47  		return encryptText;
48  	}
49  
50  	// 返回十六进制字符串
51  	private static String hex(byte[] arr) {
52  		StringBuffer sb = new StringBuffer();
53  		for (int i = 0; i < arr.length; ++i) {
54  			sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,
55  					3));
56  		}
57  		return sb.toString();
58  	}
59  
60  	public static void main(String[] args) {
61  		// md5加密测试
62  		String md5_1 = md5("yjf_123456789.11.88");
63  		System.out.println("-------->" + md5_1);
64  		// String md5_2 = md5("abc");
65  		// System.out.println(md5_1 + "\n" + md5_2);
66  		// System.out.println("md5 length: " + md5_1.length());
67  		// //sha加密测试
68  		// String sha_1 = sha("123");
69  		// String sha_2 = sha("abc");
70  		// System.out.println(sha_1 + "\n" + sha_2);
71  		// System.out.println("sha length: " + sha_1.length());
72  	}
73  }