代码之家  ›  专栏  ›  技术社区  ›  Jack

在Java中获取文件的MD5校验和

  •  568
  • Jack  · 技术社区  · 17 年前

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

    这是怎么做到的?

    22 回复  |  直到 3 年前
        1
  •  575
  •   erickson    10 年前

    有一个输入流装饰器, 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();
    
        2
  •  322
  •   leif.gruenwoldt    7 年前

    使用 DigestUtils 来自 Apache Commons Codec 图书馆:

    try (InputStream is = Files.newInputStream(Paths.get("file.zip"))) {
        String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);
    }
    
        3
  •  170
  •   Bill the Lizard    8 年前

    有一个例子 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();
           }
       }
    }
    
        4
  •  91
  •   oluies    8 年前

    这个 com.google.common.hash API提供:

    • 适用于所有哈希函数的统一用户友好的API
    • 杂音的可种子化32位和128位实现3
    • md5()、sha1()、sha256()、sha512()适配器,只需更改一行代码即可在这些适配器之间切换,并发出杂音。
    • goodFastHash(int bits),当你不在乎使用什么算法时
    • HashCode实例的通用实用程序,如combineOrdered/combineUnordered

    阅读用户指南( IO Explained , Hashing Explained ).

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

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

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

    注意 ,所以使用 如果你不需要加密安全的校验和。另请注意 不应用于存储密码等,因为使用密码很容易暴力破解 , 相反。

    对于哈希的长期保护 Merkle signature scheme 增加了安全性,欧盟委员会赞助的后量子密码学研究小组建议使用这种密码学来长期保护量子计算机( ref ).

    注意 具有比其他碰撞率更高的碰撞率。

        5
  •  71
  •   assylias    10 年前

    使用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");
    
        6
  •  41
  •   ColinD    13 年前

    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();
    
        7
  •  33
  •   MickJ    10 年前

    好的,我必须补充一下。对于那些已经拥有Spring和Apache Commons依赖关系或计划添加它的人来说,一行实现:

    DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))
    

    For and Apache commons only选项(信用@duleshi):

    DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))
    

    希望这能帮助到别人。

        8
  •  26
  •   sunil    11 年前

    一种简单的方法,没有使用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

        9
  •  15
  •   Bill the Lizard    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();
    }
    

    这显然没有回答你关于如何专门为文件做这件事的问题,上面的答案很好地解决了这个问题。我只是花了很多时间让总和看起来像大多数应用程序的显示结果,并认为您可能会遇到同样的问题。

        10
  •  12
  •   Jam    13 年前
    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/

        11
  •  9
  •   F.X    16 年前

    我们使用的代码与上一篇文章中使用的代码类似

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

    但是,请注意使用 BigInteger.toString() 在这里,因为它将截断前导零。.. (例如,试试 s = "27" ,校验和应为 "02e74f10e0327ad868d138f2b4fdd6f0" )

    我支持使用Apache Commons Codec的建议,我用它替换了我们自己的代码。

        12
  •  9
  •   David    10 年前
    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
       }
    }
    
        13
  •  9
  •   LarsH    9 年前

    非常快&;不依赖外部库的干净Java方法:

    (如果你需要,只需将MD5替换为SHA-1、SHA-256、SHA-384或SHA-512)

    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);
    }
    
        14
  •  8
  •   Laurel Enrique    9 年前

    这里有一个方便的变体,它利用了 InputStream.transferTo() 从Java 9开始,以及 OutputStream.nullOutputStream() Java 11。它不需要外部库,也不需要将整个文件加载到内存中。

    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"
    
        15
  •  6
  •   Lukasz R.    15 年前
    String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));
    
        16
  •  6
  •   gotozero    12 年前

    另一种实现方式: Fast MD5 Implementation in Java

    String hash = MD5.asHex(MD5.getHash(new File(filename)));
    
        17
  •  6
  •   stackoverflowuser2010    9 年前

    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实用程序。

        18
  •  6
  •   BillRobertson42    7 年前

    这是一个简单的函数,它封装了Sunil的代码,因此它接受一个File作为参数。该函数不需要任何外部库,但它需要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
    
        19
  •  3
  •   Matt Brock    16 年前

    如果你使用ANT进行构建,这非常简单。将以下内容添加到build.xml中:

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

    其中jarFile是您要生成MD5的JAR,toDir是您要放置MD5文件的目录。

    More info here.

        20
  •  3
  •   Balaji Boggaram Ramanarayan    12 年前

    谷歌番石榴提供了一个新的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
    
        21
  •  1
  •   XXX    12 年前
    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();
    }