1 package com.srs.tools; 2 3 import java.math.BigInteger; 4 import java.security.MessageDigest; 5 6 /******************************************************************************* 7 * 8 * 9 * MD5加密 10 */ 11 12 public class MD5_Encoding { 13 14 /** 15 * 对字符串md5加密(小写+数字) 16 * 17 * @param str 传入要加密的字符串 18 * @return MD5加密后的字符串 19 */ 20 public static String lowerMD5(String str) { 21 try { 22 // 生成一个MD5加密计算摘要 23 MessageDigest md = MessageDigest.getInstance("MD5"); 24 // 计算md5函数 25 md.update(str.getBytes()); 26 // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 27 // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 28 return new BigInteger(1, md.digest()).toString(16); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 return null; 32 } 33 } 34 35 36 /** 37 * 对字符串md5加密(大写+数字) 38 * 39 * @param str 传入要加密的字符串 40 * @return MD5加密后的字符串 41 */ 42 43 public static String upperMD5(String s) { 44 char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; 45 46 try { 47 byte[] btInput = s.getBytes(); 48 // 获得MD5摘要算法的 MessageDigest 对象 49 MessageDigest mdInst = MessageDigest.getInstance("MD5"); 50 // 使用指定的字节更新摘要 51 mdInst.update(btInput); 52 // 获得密文 53 byte[] md = mdInst.digest(); 54 // 把密文转换成十六进制的字符串形式 55 int j = md.length; 56 char str[] = new char[j * 2]; 57 int k = 0; 58 for (int i = 0; i < j; i++) { 59 byte byte0 = md[i]; 60 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 61 str[k++] = hexDigits[byte0 & 0xf]; 62 } 63 return new String(str); 64 } catch (Exception e) { 65 e.printStackTrace(); 66 return null; 67 } 68 } 69 }