我想使用Java来获得文件的MD5校验和。我真的很惊讶,但我还没有找到任何东西,显示如何获得一个文件的MD5校验和。

这是怎么做到的?


当前回答

public static void main(String[] args) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar");

    byte[] dataBytes = new byte[1024];

    int nread = 0;
    while ((nread = fis.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);
    };
    byte[] mdbytes = md.digest();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < mdbytes.length; i++) {
        sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
    System.out.println("Digest(in hex format):: " + sb.toString());
}

或者你可以得到更多的信息 http://www.asjava.com/core-java/java-md5-example/

其他回答

com.google.common.hash API提供:

为所有哈希函数提供统一的用户友好的API murmur3的32位和128位种子实现 Md5()、sha1()、sha256()、sha512()适配器,只需更改一行代码就可以在这些适配器之间切换。 goodFastHash(int bits),用于当你不关心你使用什么算法时 HashCode实例的通用实用程序,如combineOrdered / combineUnordered

阅读用户指南(IO解释,哈希解释)。

对于您的用例,Files.hash()计算并返回文件的摘要值。

例如,sha-1摘要计算(将sha-1更改为MD5以获得MD5摘要)

HashCode hc = Files.asByteSource(file).hash(Hashing.sha1());
"SHA-1: " + hc.toString();

请注意,crc32比md5快得多,所以如果您不需要加密安全的校验和,请使用crc32。还要注意,md5不应该用来存储密码之类的东西,因为它很容易被暴力破解,对于密码,应该使用bcrypt、scrypt或sha-256来代替。

对于使用散列的长期保护,默克尔签名方案增加了安全性,由欧盟委员会赞助的后量子密码学研究小组建议使用这种密码技术来长期保护量子计算机(参考)。

请注意,crc32的碰撞率比其他的更高。

谷歌guava提供了一个新的API。找到下面的一个:

public static HashCode hash(File file,
            HashFunction hashFunction)
                     throws IOException

Computes the hash code of the file using hashFunction.

Parameters:
    file - the file to read
    hashFunction - the hash function to use to hash the data
Returns:
    the HashCode of all of the bytes in the file
Throws:
    IOException - if an I/O error occurs
Since:
    12.0

从其他答案中提取想法,这里有一个简单的代码,没有第三方依赖关系(或DatatypeConverter,在最新的jdk中更长),将其生成为与md5sum工具输出兼容的十六进制字符串:

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
...

static String calculateMD5(String path) throws IOException
{
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(Files.readAllBytes(Paths.get(path)));
        return String.format("%032x", new BigInteger(1, md.digest())); // hex, padded to 32 chars
    } catch (NoSuchAlgorithmException ex)
    {
        throw new RuntimeException(ex); // MD5 is always available so this should be impossible
    }
}

使用nio2 (Java 7+),不使用外部库:

byte[] b = Files.readAllBytes(Paths.get("/path/to/file"));
byte[] hash = MessageDigest.getInstance("MD5").digest(b);

将结果与期望的校验和进行比较:

String expected = "2252290BC44BEAD16AA1BF89948472E8";
String actual = DatatypeConverter.printHexBinary(hash);
System.out.println(expected.equalsIgnoreCase(actual) ? "MATCH" : "NO MATCH");
String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));