第四十二章:MD5加密技術
阿新 • • 發佈:2018-12-08
MD5加密技術
MD5是雜湊演算法中的一種,加密強度較為適中。雜湊演算法有下面幾個特點:
①不可逆,即使在已知加密過程的前提下,無法從密文反推回明文。
②輸出資料的長度固定。例如:MD5加密輸出資料的長度固定就是32個字元。
③輸入資料不變,輸出資料不變;輸入資料變,輸出資料都會跟著變。
/** * 執行MD5加密的工具方法 * @param soucre * @return */ public static String md5(String soucre) { // 1.對字串進行校驗 boolean checkResult = stringCheck(soucre); // 2.如果字串校驗失敗,則丟擲一個異常 if (!checkResult) { throw new RuntimeException(ACConst.MESSAGE_PWD_INVALID); } // 3.將源字串轉換為位元組陣列 byte[] inputBytes = soucre.getBytes(); // 4.獲取MessageDigest例項 String algorithm = "md5"; // 5.宣告變數儲存加密結果 byte[] outputBytes = null; try { // 6.獲取MessageDigest例項 MessageDigest digest = MessageDigest.getInstance(algorithm); // 7.執行加密 outputBytes = digest.digest(inputBytes); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // 8.把加密結果位元組陣列轉換為字串 // ①宣告StringBuilder StringBuilder builder = new StringBuilder(); // ②宣告字元陣列 char[] characters = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E','F' }; // ③遍歷outputBytes for (int i = 0; i < outputBytes.length; i++) { byte b = outputBytes[i]; // ③取當前位元組的低四位數值 int lowValue = b & 15; // ④取當前位元組的高四位數值 int highValue = (b >> 4) & 15; // ⑤使用高四位和低四位的值從characters字元陣列中取出對應的字元 char lowChar = characters[lowValue]; char highChar = characters[highValue]; // ⑥拼字串 builder.append(highChar).append(lowChar); } return builder.toString(); }