1 import java.security.MessageDigest; 2 import java.security.NoSuchAlgorithmException; 3 /* 4 * MD5 算法 5 * 6 */ 7 public class MD5 { 8 9 // 全局数组 10 private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", 11 "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; 12 13 public MD5() { 14 } 15 16 // 返回形式为数字跟字符串 17 private static String byteToArrayString(byte bByte) { 18 int iRet = bByte; 19 // System.out.println("iRet="+iRet); 20 if (iRet < 0) { 21 iRet += 256; 22 } 23 int iD1 = iRet / 16; 24 int iD2 = iRet % 16; 25 return strDigits[iD1] + strDigits[iD2]; 26 } 27 28 // 返回形式只为数字 29 private static String byteToNum(byte bByte) { 30 int iRet = bByte; 31 System.out.println("iRet1=" + iRet); 32 if (iRet < 0) { 33 iRet += 256; 34 } 35 return String.valueOf(iRet); 36 } 37 38 // 转换字节数组为16进制字串 39 private static String byteToString(byte[] bByte) { 40 StringBuffer sBuffer = new StringBuffer(); 41 for (int i = 0; i < bByte.length; i++) { 42 sBuffer.append(byteToArrayString(bByte[i])); 43 } 44 return sBuffer.toString(); 45 } 46 47 public static String GetMD5Code(String strObj) { 48 String resultString = null; 49 try { 50 resultString = new String(strObj); 51 MessageDigest md = MessageDigest.getInstance("MD5"); 52 // md.digest() 该函数返回值为存放哈希值结果的byte数组 53 resultString = byteToString(md.digest(strObj.getBytes())); 54 } catch (NoSuchAlgorithmException ex) { 55 ex.printStackTrace(); 56 } 57 return resultString; 58 } 59 }
时间: 2024-11-01 03:12:03