package **; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { /** * MD5加密算法,参数选择16还是32位 * 默认为32位 * @param plainText 需加密的文本 * @param md5Type 16/32 * @return 加密后的密文 */ public static String Md5(String plainText,String md5Type) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } if(md5Type!=null&&!md5Type.trim().equals("")&&md5Type.trim().equals("16")){ return buf.toString().substring(8, 24).toUpperCase();// 16位的加密 }else{ return buf.toString().toUpperCase();// 32位的加密大写 } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { Md5("123456","16"); System.out.println(Md5("123456","16")); Md5("123456","32"); System.out.println(Md5("123456","32")); System.out.println(Md5("123456","32").equals("E10ADC3949BA59ABBE56E057F20F883E")); System.out.println(Md5("123456","16").equals("49BA59ABBE56E057")); } }
时间: 2024-10-19 16:35:56