public class MD5Util { /** * MD5加密 * * @param str * @return * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static String md5(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(str.getBytes("utf-8")); return toHex(bytes); } catch (Exception e) { throw new RuntimeException(e); } } /** * 二进制转换为十六进制 * * @param bytes * @return */ private static String toHex(byte[] bytes) { final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); StringBuilder ret = new StringBuilder(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]); ret.append(HEX_DIGITS[bytes[i] & 0x0f]); } return ret.toString(); } /** * 加盐MD5 * * @param str * @param salt * @return */ public static String md5salt(String str, String salt) { return md5(str + salt); } /** * 两次加密 * * @param str * @return */ public static String md5_double(String str) { return md5(md5(str)); } /** * 两次加密再加盐 * * @param str * @param salt * @return */ public static String md5salt_double(String str, String salt) { return md5(md5salt(str, salt)); } public static void main(String[] args) { String str = "123456"; String salt = "zxc"; System.out.println("md5(str) = " + md5(str)); System.out.println("md5salt(str,salt) = " + md5salt(str, salt)); System.out.println("md5_double(str) = " + md5_double(str)); System.out.println("md5salt_double(str,salt) = " + md5salt_double(str, salt)); }