---
title: "Java实现的加密工具类（支持MD5和SHA）"
author: "yeuego"
date: "2011-03-09T16:48:36Z"
tags: ["JDK", "Java", "Security", "算法"]
categories: ["编程语言"]
slug: "java-md5-sha"
draft: false
lastmod: "2011-03-09T16:48:36Z"
id: 948762
url: "https://yeuego.iteye.com/blog/948762"
---

**提出问题：**MD5，SHA算法是常用的两种加密算法。以前看过很多人写的md5算法，要么过于难懂，要么过于冗长，而且不能切换为其他加密算法，非常不给力。  
     **分析和解决问题：**于是，决定自己写一个简单好用的加密算法。翻看JDK1.5的API文档，惊喜的发现，在java.security这个包下面有一个MessageDigest类：此 MessageDigest 类为应用程序提供信息摘要算法的功能，如 MD5 或 SHA 算法。bingo！参考了部分网友的代码，本人的代码如下，不足之处，请大家批评指正。**JDK/JRE版本：**1.5+

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/855357 "复制代码")

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

```
package common.util.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptUtil {

	public static void main(String[] args) {
		//md5加密测试
		String md5_1 = md5("123");
		String md5_2 = md5("abc");
		System.out.println(md5_1 + "\n" + md5_2);
		System.out.println("md5 length: " + md5_1.length());
		//sha加密测试
		String sha_1 = sha("123");
		String sha_2 = sha("abc");
		System.out.println(sha_1 + "\n" + sha_2);
		System.out.println("sha length: " + sha_1.length());
	}

	// md5加密
	public static String md5(String inputText) {
		return encrypt(inputText, "md5");
	}

	// sha加密
	public static String sha(String inputText) {
		return encrypt(inputText, "sha-1");
	}

	/**
	 * md5或者sha-1加密
	 * 
	 * @param inputText
	 *            要加密的内容
	 * @param algorithmName
	 *            加密算法名称：md5或者sha-1，不区分大小写
	 * @return
	 */
	private static String encrypt(String inputText, String algorithmName) {
		if (inputText == null || "".equals(inputText.trim())) {
			throw new IllegalArgumentException("请输入要加密的内容");
		}
		if (algorithmName == null || "".equals(algorithmName.trim())) {
			algorithmName = "md5";
		}
		String encryptText = null;
		try {
			MessageDigest m = MessageDigest.getInstance(algorithmName);
			m.update(inputText.getBytes("UTF8"));
			byte s[] = m.digest();
			// m.digest(inputText.getBytes("UTF8"));
			return hex(s);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encryptText;
	}

	// 返回十六进制字符串
	private static String hex(byte[] arr) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arr.length; ++i) {
			sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,
					3));
		}
		return sb.toString();
	}
```

 

运行结果代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/855357 "复制代码")

1. 上述代码的运行结果：
2. 202cb962ac59075b964b07152d234b70
3. 900150983cd24fb0d6963f7d28e17f72
4. md5 length: 32
5. 40bd001563085fc35165329ea1ff5c5ecbdbbeef
6. a9993e364706816aba3e25717850c26c9cd0d89d
7. sha length: 40

```
上述代码的运行结果：
202cb962ac59075b964b07152d234b70
900150983cd24fb0d6963f7d28e17f72
md5 length: 32
40bd001563085fc35165329ea1ff5c5ecbdbbeef
a9993e364706816aba3e25717850c26c9cd0d89d
sha length: 40
```

    由此可见，MD5和SHA-1加密后生成的字符串长度分别为32和40。