Pobieranie sumy kontrolnej MD5 pliku w Javie

Szukam Javy, aby uzyskać sumę kontrolną MD5 pliku. Byłem naprawdę zaskoczony, ale nie byłem w stanie znaleźć niczego, co pokazuje, jak uzyskać sumę kontrolną MD5 pliku.

Jak to się robi?

Author: Hamedz, 2008-11-20

21 answers

Istnieje dekorator strumienia wejściowego, java.security.DigestInputStream, dzięki któremu można obliczyć digest podczas korzystania ze strumienia wejściowego, jak zwykle, zamiast wykonywać dodatkowe przejście nad danymi.

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();
 560
Author: erickson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-21 16:01:56

Użyj DigestUtils z Apache Commons Codec library:

try (InputStream is = Files.newInputStream(Paths.get("file.zip"))) {
    String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);
}
 308
Author: Leif Gruenwoldt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-08 20:46:39

Jest przykład w Real ' S Java-How-to używając KlasyMessageDigest .

Sprawdź tę stronę pod kątem przykładów z użyciem CRC32 i 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();
       }
   }
}
 169
Author: Bill the Lizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-06 01:59:54

Kom.google.pospolite.hash oferty API:

  • unified user-friendly API for all hash functions
  • Seedable 32 - i 128-bitowe implementacje murmur3
  • Adaptery md5 (), sha1 (), sha256 (), sha512 (), zmieniają tylko jedną linijkę kodu, aby przełączać się między nimi, a szmerem.
  • goodFastHash (int bits), gdy nie obchodzi cię, jakiego algorytmu używasz
  • ogólne narzędzia dla instancji HashCode, takie jak combineOrdered / combineUnordered

Przeczytaj Podręcznik użytkownika (IO Explained, Hashing Explained ).

Dla Twojego przypadku użycia Files.hash() oblicza i zwraca wartość digest dla pliku.

Na przykład a SHA-1 obliczanie digest (Zmień SHA - 1 na MD5, aby uzyskać MD5 digest)

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

Zauważ, że crc32 jest znacznie szybszy niż md5 , więc użyj crc32, Jeśli nie potrzebujesz kryptograficznie zabezpieczonej sumy kontrolnej. Zauważ również, że md5 nie powinien być używany do przechowywania haseł i tym podobnych, ponieważ jest to łatwe do brutalnej siły, dla haseł używać bcrypt, zamiast tego scrypt lub sha-256 .

Dla długoterminowej ochrony z hashami a Merkle Signature scheme dodaje do bezpieczeństwa i Post Quantum Cryptography Study Group sponsorowana przez Komisję Europejską zaleciła użycie tej kryptografii do długoterminowej ochrony przed komputerami kwantowymi ( ref ).

Zauważ, że crc32 ma wyższy współczynnik kolizji niż pozostałe.

 91
Author: oluies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-15 21:20:23

Używanie nio2 (Java 7+) i brak zewnętrznych bibliotek:

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

Aby porównać wynik z oczekiwaną sumą kontrolną:

String expected = "2252290BC44BEAD16AA1BF89948472E8";
String actual = DatatypeConverter.printHexBinary(hash);
System.out.println(expected.equalsIgnoreCase(actual) ? "MATCH" : "NO MATCH");
 63
Author: assylias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-23 10:30:11

Guava udostępnia teraz nowe, spójne API hashujące, które jest znacznie bardziej przyjazne dla użytkownika niż różne interfejsy API hashujące dostępne w JDK. Zobacz Hashing Explained . Dla pliku można łatwo uzyskać sumę MD5, CRC32 (z wersją 14.0+) lub wiele innych skrótów:

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();
 40
Author: ColinD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-04 15:36:07

Ok. Musiałem dodać. Implementacja jednej linii dla tych, którzy już mają zależność Spring i Apache Commons lub planują ją dodać:

DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))

For and Apache commons only option (credit @duleshi):

DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))
Mam nadzieję, że to komuś pomoże.
 32
Author: MickJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-07 15:43:53

Proste podejście bez bibliotek stron trzecich używających Java 7

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

Jeśli chcesz wydrukować tablicę bajtów. Użyj jak poniżej

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

Jeśli potrzebujesz sześciokątnego sznurka z tego trawienia. Użyj jak poniżej

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

Gdzie DatatypeConverter to javax.xml.bind.DatatypeConverter

 24
Author: sunil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-31 08:23:19

Ostatnio musiałem to zrobić tylko dla dynamicznego ciągu, MessageDigest może reprezentować hash na wiele sposobów. Aby uzyskać podpis pliku, jak można uzyskać z md5sum Komenda musiałem zrobić coś takiego:

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

To oczywiście nie odpowiada na twoje pytanie, Jak to zrobić specjalnie dla pliku, powyższa odpowiedź radzi sobie z tym spokojnie. Po prostu spędziłem dużo czasu, aby suma wyglądała jak większość aplikacji wyświetla ją i pomyślałem, że może wpaść w te same kłopoty.

 14
Author: Brian Gianforcaro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-05 22:42:19
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());
}

Lub możesz uzyskać więcej informacji http://www.asjava.com/core-java/java-md5-example/

 11
Author: Jam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-31 06:22:55
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
   }
}
 9
Author: F.X,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-12 15:43:28

Bardzo szybka i czysta Java-metoda, która nie opiera się na zewnętrznych bibliotekach:

(po prostu zastąp MD5 SHA - 1, SHA-256, SHA-384 lub SHA-512, jeśli chcesz)

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);
}
 9
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-07 21:05:11
String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));
 9
Author: Ravikiran kalal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-27 22:01:55

Używaliśmy kodu, który przypomina powyższy kod w poprzednim poście używając

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

Uważaj jednak na użycie BigInteger.toString() tutaj, ponieważ spowoduje to obcięcie zer wiodących... (dla przykładu spróbuj s = "27", suma kontrolna powinna być "02e74f10e0327ad868d138f2b4fdd6f0")

Popieram sugestię użycia kodeka Apache Commons, zastąpiłem nim nasz własny kod.

 9
Author: user552999,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-05 19:42:02

Kolejna implementacja: Szybka implementacja MD5 w Javie

String hash = MD5.asHex(MD5.getHash(new File(filename)));
 6
Author: Lukasz R.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-16 13:10:27

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;
  }
}

Wynik jest równy linuksowemu narzędziu md5sum.

 6
Author: gotozero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-17 12:43:08

Oto prosta funkcja, która otacza Kod Sunila tak, że pobiera plik jako parametr. Funkcja nie wymaga żadnych zewnętrznych bibliotek, ale wymaga Javy 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);            
    }


}

Przykładowe wyjście:

hex=B117DD0C3CBBD009AC4EF65B6D75C97B
 6
Author: stackoverflowuser2010,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-09 22:25:40

Oto przydatna odmiana, która wykorzystuje {[3] } z Javy 9 i {[4] } z Javy 11. Nie wymaga zewnętrznych bibliotek i nie wymaga ładowania całego pliku do pamięci.

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

I

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

Zwraca

"e30fa2784ba15be37833d569280e2163c6f106506dfb9b07dde67a24bfb90da65c661110cf2c5c6f71185754ee5ae3fd83a5465c92f72abd888b03187229da29"
 6
Author: Bill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-08 22:27:06

Jeśli używasz ANT do budowania, to jest to ŚMIERTELNIE PROSTE. Dodaj następujące elementy do swojej kompilacji.xml:

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

Gdzie jarFile jest JAR, dla którego chcesz wygenerować MD5, a toDir jest katalogiem, w którym chcesz umieścić plik MD5.

Więcej informacji tutaj.

 3
Author: Matt Brock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-09 20:04:05

Google guava udostępnia nowe API. Znajdź ten poniżej:

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
 3
Author: Balaji Boggaram Ramanarayan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-23 23:37:19
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
Author: XXX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-24 06:54:02