获得文件的MD5校验和Java中

问题描述 投票:461回答:21

我期待使用Java获得文件的MD5校验和。我真的很惊讶,但我一直没能找到任何说明如何获取一个文件的MD5校验。

它是如何做?

java md5 checksum
21个回答
521
投票

同时使用,而不必使对数据的额外通输入流像往常一样,有一个输入流装饰,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();

11
投票
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/


9
投票

我们使用的是类似于使用上面的代码中一前一后的代码

...
String signature = new BigInteger(1,md5.digest()).toString(16);
...

但是,注意使用BigInteger.toString()这里,因为它会截断前导零...(为例,尝试s = "27",校验应该"02e74f10e0327ad868d138f2b4fdd6f0"

我第二次使用Apache共享编解码器的建议,我换成我们自己的代码这一点。


8
投票

非常快速和干净Java的方法,它不依赖于外部库:

(只需使用SHA-1,SHA-256,SHA-384和SHA-512,如果你想更换那些MD5)

public String calcMD5() throws Exception{
        byte[] buffer = new byte[8192];
        MessageDigest md = MessageDigest.getInstance("MD5");

        DigestInputStream dis = new DigestInputStream(new FileInputStream(new File("Path to file")), md);
        try {
            while (dis.read(buffer) != -1);
        }finally{
            dis.close();
        }

        byte[] bytes = md.digest();

        // bytesToHex-method
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }

        return new String(hexChars);
}

7
投票
public static String MD5Hash(String toHash) throws RuntimeException {
   try{
       return String.format("%032x", // produces lower case 32 char wide hexa left-padded with 0
      new BigInteger(1, // handles large POSITIVE numbers 
           MessageDigest.getInstance("MD5").digest(toHash.getBytes())));
   }
   catch (NoSuchAlgorithmException e) {
      // do whatever seems relevant
   }
}

7
投票
String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));

6
投票

另一种实现:Fast MD5 Implementation in Java

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

6
投票

Standard Java Runtime Environment way

public String checksum(File file) {
  try {
    InputStream fin = new FileInputStream(file);
    java.security.MessageDigest md5er =
        MessageDigest.getInstance("MD5");
    byte[] buffer = new byte[1024];
    int read;
    do {
      read = fin.read(buffer);
      if (read > 0)
        md5er.update(buffer, 0, read);
    } while (read != -1);
    fin.close();
    byte[] digest = md5er.digest();
    if (digest == null)
      return null;
    String strDigest = "0x";
    for (int i = 0; i < digest.length; i++) {
      strDigest += Integer.toString((digest[i] & 0xff) 
                + 0x100, 16).substring(1).toUpperCase();
    }
    return strDigest;
  } catch (Exception e) {
    return null;
  }
}

结果等于的Linux的md5sum效用。


6
投票

这里是如此,它需要一个文件作为一个参数,环绕苏尼尔的代码的简单功能。该功能不需要任何外部库,但它确实需要Java 7。

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.bind.DatatypeConverter;

public class Checksum {

    /**
     * Generates an MD5 checksum as a String.
     * @param file The file that is being checksummed.
     * @return Hex string of the checksum value.
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static String generate(File file) throws NoSuchAlgorithmException,IOException {

        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(Files.readAllBytes(file.toPath()));
        byte[] hash = messageDigest.digest();

        return DatatypeConverter.printHexBinary(hash).toUpperCase();
    }

    public static void main(String argv[]) throws NoSuchAlgorithmException, IOException {
        File file = new File("/Users/foo.bar/Documents/file.jar");          
        String hex = Checksum.generate(file);
        System.out.printf("hex=%s\n", hex);            
    }


}

示例输出:

hex=B117DD0C3CBBD009AC4EF65B6D75C97B

3
投票

如果您使用Ant来构建,这是死简单。以下添加到您的build.xml:

<checksum file="${jarFile}" todir="${toDir}"/>

其中jar文件是要产生针对MD5的JAR和toDir是目录要放置的MD5文件。

More info here.


3
投票

谷歌番石榴提供了一个新的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

291
投票

DigestUtils库使用Apache Commons Codec

try (InputStream is = Files.newInputStream(Paths.get("file.zip"))) {
    String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);
}

2
投票
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();
}

2
投票

下面是从Java 11.不需要外部库,也不需要将整个文件加载到内存中一个方便的变化,使得使用InputStream.transferTo()的从Java 9,和OutputStream.nullOutputStream()

public static String hashFile(String algorithm, File f) throws IOException, NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance(algorithm);

    try(BufferedInputStream in = new BufferedInputStream((new FileInputStream(f)));
        DigestOutputStream out = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {
        in.transferTo(out);
    }

    String fx = "%0" + (md.getDigestLength()*2) + "x";
    return String.format(fx, new BigInteger(1, md.digest()));
}

hashFile("SHA-512", Path.of("src", "test", "resources", "some.txt").toFile());

回报

"e30fa2784ba15be37833d569280e2163c6f106506dfb9b07dde67a24bfb90da65c661110cf2c5c6f71185754ee5ae3fd83a5465c92f72abd888b03187229da29"

157
投票

有使用Real's Java-How-to类在MessageDigest一个例子。

检查使用CRC32和SHA-1以及示例页面。

import java.io.*;
import java.security.MessageDigest;

public class MD5Checksum {

   public static byte[] createChecksum(String filename) throws Exception {
       InputStream fis =  new FileInputStream(filename);

       byte[] buffer = new byte[1024];
       MessageDigest complete = MessageDigest.getInstance("MD5");
       int numRead;

       do {
           numRead = fis.read(buffer);
           if (numRead > 0) {
               complete.update(buffer, 0, numRead);
           }
       } while (numRead != -1);

       fis.close();
       return complete.digest();
   }

   // see this How-to for a faster way to convert
   // a byte array to a HEX string
   public static String getMD5Checksum(String filename) throws Exception {
       byte[] b = createChecksum(filename);
       String result = "";

       for (int i=0; i < b.length; i++) {
           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
       }
       return result;
   }

   public static void main(String args[]) {
       try {
           System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));
           // output :
           //  0bb2827c5eacf570b6064e24e0e6653b
           // ref :
           //  http://www.apache.org/dist/
           //          tomcat/tomcat-5/v5.5.17/bin
           //              /apache-tomcat-5.5.17.exe.MD5
           //  0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
}

86
投票

com.google.common.hash API提供:

  • 所有散列函数统一的用户友好API
  • murmur3的Seedable 32位和128位的情况
  • MD5(),SHA1(),SHA256(),SHA512()适配器,仅改变一行代码杂音这些之间进行切换,和。
  • goodFastHash(INT位),因为当你不关心你用什么算法
  • 为的hashCode情况下,像combineOrdered / combineUnordered通用工具

阅读用户指南(IO ExplainedHashing Explained)。

为了您的用例Files.hash()计算和文件返回摘要值。

例如摘要计算(变更SHA-1到MD5得到MD5摘要)

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

需要注意的是快得多,所以使用如果你不需要密码安全校验。还要注意的是不应该被用来存储密码之类,因为它是很容易蛮力,口令使用代替。

对于哈希长期保护Merkle signature scheme增加了安全性和岗位量子密码学研究小组由欧洲委员会资助的建议使用这种加密技术针对量子计算机的长期保护(ref)。

需要注意的是具有更高的碰撞速度比其他人。


55
投票

使用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");

38
投票

Guava现在提供了一个新的,一致性哈希的API,它是更加人性化比JDK提供的各种散列的API。见Hashing Explained。对于文件,你可以得到的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();

28
投票

好。我不得不添加。对于那些谁已经有Spring和Apache共享依赖或正在计划将其添加一号线实现:

DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))

对于和Apache下议院唯一的选择(信用@duleshi):

DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))

希望这可以帮助别人。


23
投票

使用Java 7没有第三方库的简单方法

String path = "your complete file path";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(path)));
byte[] digest = md.digest();

如果您需要打印此字节数组。使用如下

System.out.println(Arrays.toString(digest));

如果你需要的十六进制字符串出这个消化的。使用如下

String digestInHex = DatatypeConverter.printHexBinary(digest).toUpperCase();
System.out.println(digestInHex);

其中DatatypeConverter是javax.xml.bind.DatatypeConverter


13
投票

我最近不得不只是一个动态字符串做到这一点,MessageDigest可以代表多种方式的哈希值。要获取文件的签名像你将与md5sum命令让我不得不做一些像这样的:

try {
   String s = "TEST STRING";
   MessageDigest md5 = MessageDigest.getInstance("MD5");
   md5.update(s.getBytes(),0,s.length());
   String signature = new BigInteger(1,md5.digest()).toString(16);
   System.out.println("Signature: "+signature);

} catch (final NoSuchAlgorithmException e) {
   e.printStackTrace();
}

这显然不回答有关如何做到这一点专门为一个文件,与安静很好上述答案的交易问题。我只是花了很多时间去总和看起来像大多数应用程序的显示它,觉得你可能会遇到同样的麻烦。

© www.soinside.com 2019 - 2024. All rights reserved.