生成十六进制MD5

import java.security.MessageDigest;

public class MD5Util {
	/**
	 * MD5(32位的十六进制表示)
	 * 
	 * @param srcStr
	 *            源字符串
	 * @param encode
	 *            编码方式
	 * @return
	 */
	public static String digest(String srcStr, String encode) {
		MessageDigest md = null;
		byte[] bytes = null;
		try {
			md = MessageDigest.getInstance("MD5");
			if (encode == null)
				bytes = md.digest(srcStr.getBytes());
			else
				bytes = md.digest(srcStr.getBytes(encode));
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < bytes.length; i++) {
				byte b = bytes[i];
				if ((b & 0xff) < 0xf) {
					sb.append("0");
				}
				sb.append(Integer.toHexString(b & 0xff));
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";

	}

	/**
	 * MD5(32位的十六进制表示)
	 * 
	 * @param srcStr
	 *            源字符串
	 * @return
	 */
	public static String digest(String srcStr) {
		return digest(srcStr, null);
	}

	public static void main(String[] args) {
		String str = "tanajiya";
		System.out.println(digest(str));
	}
}
 

你可能感兴趣的:(Security)