實現代碼:
public class Main { public static void main(String[] args) throws Exception { System.out.println(stringToMD5("hello world!")); } public static String stringToMD5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException { // 返回實現MD5算法的 MessageDigest對象 MessageDigest md = MessageDigest.getInstance("MD5"); // 使用UTF-8字符集將此String編碼到byte序列 byte[] byte_arr = str.getBytes("UTF-8"); // digest(byte[])方法通過執行填充等最終操作來完成哈希計算,計算結果為一個byte數組,接下來將這個數組轉換為16進制的字符串 return bytesToHexString(md.digest(byte_arr)); } public static String bytesToHexString(byte[] byte_arr) { StringBuffer res_sb = new StringBuffer(); String temp; for (byte b : byte_arr) { // 將byte數組中的每一個字節先轉換為int然后與十六進制下的FF進行按位與運算 // Integer.toHexString的參數是int,如果不進行上述運算,那么當一個byte會轉換成int時,對於負數,會做位擴展, // 例如:一個byte類型的-1(即0xFF),會被轉換成int 類型的-1(即0xFFFFFFFF) temp = Integer.toHexString((int)b & 0xFF); // 如果運算后的結果不足兩位補上最高位0 if (temp.length() < 2) { res_sb.append("0"); } res_sb.append(temp.toUpperCase()); } return res_sb.toString(); } }
參考: