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

这是怎么做到的?


当前回答

有一个输入流装饰器,java。security。DigestInputStream,这样您就可以像往常一样在使用输入流时计算摘要,而不必对数据进行额外的传递。

MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"));
     DigestInputStream dis = new DigestInputStream(is, md)) 
{
  /* Read decorated stream (dis) to EOF as normal... */
}
byte[] digest = md.digest();

其他回答

public static String getMd5OfFile(String filePath)
{
    String returnVal = "";
    try 
    {
        InputStream   input   = new FileInputStream(filePath); 
        byte[]        buffer  = new byte[1024];
        MessageDigest md5Hash = MessageDigest.getInstance("MD5");
        int           numRead = 0;
        while (numRead != -1)
        {
            numRead = input.read(buffer);
            if (numRead > 0)
            {
                md5Hash.update(buffer, 0, numRead);
            }
        }
        input.close();

        byte [] md5Bytes = md5Hash.digest();
        for (int i=0; i < md5Bytes.length; i++)
        {
            returnVal += Integer.toString( ( md5Bytes[i] & 0xff ) + 0x100, 16).substring( 1 );
        }
    } 
    catch(Throwable t) {t.printStackTrace();}
    return returnVal.toUpperCase();
}
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/

Guava现在提供了一个新的、一致的哈希API,它比JDK中提供的各种哈希API更友好。参见哈希的解释。对于一个文件,你可以很容易地得到MD5和,CRC32(14.0+版本)或许多其他哈希值:

HashCode md5 = Files.hash(file, Hashing.md5());
byte[] md5Bytes = md5.asBytes();
String md5Hex = md5.toString();

HashCode crc32 = Files.hash(file, Hashing.crc32());
int crc32Int = crc32.asInt();

// the Checksum API returns a long, but it's padded with 0s for 32-bit CRC
// this is the value you would get if using that API directly
long checksumResult = crc32.padToLong();

另一种实现:Java中的快速MD5实现

String hash = MD5.asHex(MD5.getHash(new File(filename)));

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的碰撞率比其他的更高。