轉自:https://blog.csdn.net/jay314159/article/details/4918358
前言:
MD5即Message-Digest Algorithm 5(信息-摘要算法 5),用於確保信息傳輸完整一致。是計算機廣泛使用的算法之一,主流的編程語言均有MD5的實現。
將數據(字符串)運算為另一固定長度值是加密的基本原理,MD5的前身有MD2、MD3、MD4。
本文介紹使用MD5進行加密和驗證,將原本的字符串通過MD5加密后成另一個字符串,而且根據新的字符串無法獲得原字符串,但可以在不知道原始密碼的情況下進行驗證。
關鍵技術:
通過java.security.MessageDigest的靜態方法getInstance創建具有指定算法名稱的信息摘要,參數為算法名,傳入"MD5"則表明要使用MD5算法。
MessageDigest的digest實例方法使用指定的字節數組對摘要進行最后更新,然后完成摘要計算,返回存放哈希值結果的季節數組,這個數組就是MD5加密產品。
將加密后的字節數組轉換成十六進制的字符竄,形成最終的密碼。
當輸入字符串經過MD5加密后,得到的字符串與密碼一樣,則認為密碼驗證通過。
實例演示:
package com.zhanzhuang.md5; import java.security.MessageDigest; /** * @author zhan zhuang * @time 2018年6月8日下午1:48:06 * */ public class Encryption { public static void main(String[] args) { String password = Encryption.createPassword("123456"); System.out.println("對123456用MD5加密后的密碼為:" + password); String inputstr = "1234"; System.out.println("1234與密碼相同?" + Encryption.authenticatePassword(password, inputstr)); inputstr = "123456"; System.out.println("123456與密碼相同?" + Encryption.authenticatePassword(password, inputstr)); } // 16進制下數字到字符的映射數組 private static String[] hexDigits = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; // 將inputstr加密的方法 public static String createPassword(String inputstr) { return encodeByMD5(inputstr); } // 驗證密碼是否正確 public static boolean authenticatePassword(String pass, String inputstr) { if (pass.equals((encodeByMD5(inputstr)))) { return true; } else { return false; } } // 對字符串進行MD5編碼 private static String encodeByMD5(String originstr) { if (originstr != null) { try { // 創建具有指定算法名稱的信息摘要 MessageDigest md = MessageDigest.getInstance("MD5"); // 使用指定的字節數組對摘要進行最后的更新,然后完成摘要計算 byte[] results = md.digest(originstr.getBytes()); // 將得到的字節數組編程字符串返回 String resultString = byteArrayToHexString(results); return resultString.toUpperCase(); } catch (Exception ex) { ex.printStackTrace(); } } return null; } // 轉換字節數組為十六進制字符串 private static String byteArrayToHexString(byte[] b) { StringBuffer resultsb = new StringBuffer(); int i = 0; for (i = 0; i < b.length; i++) { resultsb.append(byteToHexString(b[i])); } return resultsb.toString(); } // 將字節轉化成十六進制的字符串 private static String byteToHexString(byte b) { int n = b; if (n < 0) { n = 256 + n; } int d1 = n / 16; int d2 = n / 16; return hexDigits[d1] + hexDigits[d2]; } }