JAVA獲取檔案MD5值
阿新 • • 發佈:2019-01-28
/** * Md5校驗工具類 * @author Fengwx */ public class MD5Util { private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; /** * Get MD5 of a file (lower case) * @return empty string if I/O error when get MD5 */ @NonNull public static String getFileMD5(@NonNull File file) { FileInputStream in = null; try { in = new FileInputStream(file); FileChannel ch = in.getChannel(); return MD5(ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length())); } catch (FileNotFoundException e) { return ""; } catch (IOException e) { return ""; } finally { if (in != null) { try { in.close(); } catch (IOException e) { // 關閉流產生的錯誤一般都可以忽略 } } } } /** * MD5校驗字串 * @param s String to be MD5 * @return 'null' if cannot get MessageDigest */ @NonNull private static String getStringMD5(@NonNull String s) { MessageDigest mdInst; try { // 獲得MD5摘要演算法的 MessageDigest 物件 mdInst = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } byte[] btInput = s.getBytes(); // 使用指定的位元組更新摘要 mdInst.update(btInput); // 獲得密文 byte[] md = mdInst.digest(); // 把密文轉換成十六進位制的字串形式 int length = md.length; char str[] = new char[length * 2]; int k = 0; for (byte b : md) { str[k++] = hexDigits[b >>> 4 & 0xf]; str[k++] = hexDigits[b & 0xf]; } return new String(str); } @NonNull private static String getSubStr(@NonNull String str, int subNu, char replace) { int length = str.length(); if (length > subNu) { str = str.substring(length - subNu, length); } else if (length < subNu) { // NOTE: padding字元填充在字串的右側,和伺服器的演算法是一致的 str += createPaddingString(subNu - length, replace); } return str; } @NonNull private static String createPaddingString(int n, char pad) { if (n <= 0) { return ""; } char[] paddingArray = new char[n]; Arrays.fill(paddingArray, pad); return new String(paddingArray); } /** * 計算MD5校驗 * @param buffer * @return 空串,如果無法獲得 MessageDigest例項 */ @NonNull private static String MD5(ByteBuffer buffer) { String s = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(buffer); byte tmp[] = md.digest(); // MD5 的計算結果是一個 128 位的長整數, // 用位元組表示就是 16 個位元組 char str[] = new char[16 * 2]; // 每個位元組用 16 進製表示的話,使用兩個字元, // 所以表示成 16 進位制需要 32 個字元 int k = 0; // 表示轉換結果中對應的字元位置 for (int i = 0; i < 16; i++) { // 從第一個位元組開始,對 MD5 的每一個位元組 // 轉換成 16 進位制字元的轉換 byte byte0 = tmp[i]; // 取第 i 個位元組 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取位元組中高 4 位的數字轉換, >>>, // 邏輯右移,將符號位一起右移 str[k++] = hexDigits[byte0 & 0xf]; // 取位元組中低 4 位的數字轉換 } s = new String(str); // 換後的結果轉換為字串 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return s; } }
可直接Md5Util.getFileMD5(new File(''filepath')) 將輸出結果與http://www.atool.org/file_hash.php中計算的檔案md5對比,發現所得值相同。