欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MD5加密工具类

程序员文章站 2024-03-19 09:29:34
...
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 * 
 * @author 宋陆
 * @date 2013-10-8
 * @version 1.0
 */
public class Md5Util {

	/**
	 * Md5.
	 *
	 * @param value the value
	 * @return the string
	 */
	public static String md5(String value) {
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] e = md.digest(value.getBytes());
			return toHex(e);
		}
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return value;
		}
	}
	
	/**
	 * Md5.
	 *
	 * @param bytes the bytes
	 * @return the string
	 */
	public static String md5(byte[] bytes){
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] e = md.digest(bytes);
			return toHex(e);
		}
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * To hex.
	 *
	 * @param bytes the bytes
	 * @return the string
	 */
	private static String toHex(byte bytes[]){
		StringBuilder hs = new StringBuilder();
		String stmp = "";
		for (int n = 0; n < bytes.length; n++) {
			stmp = Integer.toHexString(bytes[n] & 0xff);
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString();
	}
}