代碼一:
/** * 實作MD5加密* */public class MD5 { /** * 取得加密後的字串* @param input * @return */ public static String stringMD5(String pw) { try { // 拿一個MD5轉換器(如果想要SHA1參數換成”SHA1”) MessageDigest messageDigest =MessageDigest.getInstance("MD5"); //輸入的字串轉換成位元組數組byte[] inputByteArray = pw.getBytes(); // inputByteArray是輸入字串轉換得到的位元組數組messageDigest.update(inputByteArray); // 轉換並傳回結果,也是位元組數組,包含16個元素byte[] resultByteArray = messageDigest.digest(); //字元陣列轉換成字串回傳return byteArrayToHex(resultByteArray); } catch (NoSuchAlgorithmException e) { return null; } } public static String byteArrayToHex(byte[] byteArray) { // 先初始化每個字元陣列,用來存放每個字元陣列,初始化每個字元陣列1616進位字元char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B',' C','D','E','F' }; // new一個字元數組,這個就是用來組成結果字串的(解釋一下:一個byte是八位二進制,也就是2位十六進製字符(2的8次方等於16的2次方)) char[] resultCharArray =new char[byteArray.length * 2]; // 遍歷位元組數組,透過位元運算(位元運算效率高),轉換成字元放到字元陣列中去int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b>>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b& 0xf]; } // 字元陣列組合成字串回傳return new String(resultCharArray); }}
方法二:
package other;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/* * MD5 演算法*/public class MD5 { // 全域陣列private final static String[] strDigits = { "0", "1", " 2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public MD5() { } // 回傳形式為數字跟字串private static String byteToArrayString(byte bByte) { int iRet = bByte; // System.out.println("iRet="+iRet); if (iRet < 0) { iRet += 256; } int iD1 = iRet / 16; int iD2 = iRet % 16; return strDigits[iD1] + strDigits[iD2]; } // 傳回形式只為數字private static String byteToNum(byte byte); System.out.println("iRet1=" + iRet); if (iRet < 0) { iRet += 256; } return String.valueOf(iRet); } // 轉換位元組數組為16進位字符串private static String byteToString(byte[] bByte) { StringBuffer sBuffer = new StringBuffer(); for (int i = 0; i < bByte.length; i++) { sBuffer.append(byteToArrayString(bByte[i])); } return sBuffer.toString(); } public static String GetMD5Code(String strObj) { String resultString = null; try { resultString = new String(Obj); md = MessageDigest.getInstance("MD5"); // md.digest() 該函數返回值為存放哈希值結果的byte數組resultString = byteToString(md.digest(strObj.getBytes())); } catch (NoSuchAlgorithmException ex ) { ex.printStackTrace(); } return resultString; } public static void main(String[] args) { MD5 getMD5 = new MD5(); System.out.println(getMD5.GetMD5Code("000000")); }}