需要替小檔案算個 MD5 時,Java 世界裡最常見的有兩條路:一是 JDK 自帶的 MessageDigest,搭配 NIO 的記憶體映射把整檔一次讀進來;二是 Apache Commons Codec 提供的 DigestUtils,一行就能收尾。兩者結果一致,風格差很多。
這個版本把檔案映射成唯讀的位元組緩衝區,再交給 MessageDigest 更新,最後用 BigInteger 轉成十六進位字串。
package cdm;
import java.io.*;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import org.apache.commons.codec.digest.*;
import org.apache.commons.io.IOUtils;
public class testMD5 {
public static String getMd5ByFile(File file) throws FileNotFoundException {
String value = null;
FileInputStream in = new FileInputStream(file);
try {
MappedByteBuffer byteBuffer = in.getChannel()
.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteBuffer);
BigInteger bi = new BigInteger(1, md5.digest());
value = bi.toString(16);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try { in.close(); } catch (IOException e) { e.printStackTrace(); }
}
}
return value;
}
public static void main(String[] args) throws IOException {
String path = "E:\\commons-codec-1.9-bin.zip";
String v = getMd5ByFile(new File(path));
System.out.println("MD5:" + v.toUpperCase());
FileInputStream fis = new FileInputStream(path);
String md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));
IOUtils.closeQuietly(fis);
System.out.println("MD5:" + md5);
}
}
MappedByteBuffer 的路子看起來專業,但有兩個務實的缺點:它一次把整個檔案對映進位址空間,檔案一大就不合適;另外 BigInteger.toString(16) 遇到前導零會被吃掉,導致雜湊值少一位,實務上需要自己補零。Commons Codec 的 md5Hex 則直接處理好補零與大小寫,程式碼也短得多。
值得一提的是,MD5 已被證明不適合當作安全性用途(例如存放密碼或簽章驗證),它適合用來做「檔案有沒有被意外改動」的完整性比對。若需要抗碰撞的雜湊,請改用 SHA-256 以上。
執行結果與官方提供的 MD5 值相符。commons-codec 的 jar 可從 Apache 官方網站下載;若要處理超過 1 GB 以上的大檔,建議改用串流分段更新的方式,而不是一次讀進記憶體。