67

What is the fastest way to create a hash function which will be used to check if two files are equal?

Security is not very important.

Edit: I am sending a file over a network connection, and will be sure that the file on both sides are equal

Jon Seigel
  • 11,819
  • 8
  • 53
  • 90
eflles
  • 5,890
  • 10
  • 38
  • 54
  • 14
    A hash function can't tell you if two files are equal. It can only tell you if two files are *not* equal. If you're only comparing two files once, faster than any hash algorithm will be simple reading the files and comparing them. – jemfinch May 17 '10 at 04:47
  • 9
    @jemfinch: the hash function is a faster way to disprove that files are the same if they are not on the same filesystem. – dotancohen Feb 17 '15 at 16:15
  • 5
    As long as the probability, of the hash failing to disprove that the files are equal, is less than the sum of the probabilities of all the other things that can go wrong (e.g. computer failure), then all is well. For a 256 bit hash it may be more likely that your computer turns in to a cat (larger animals are very unlikely), or a bowl of petunias. – ctrl-alt-delor May 01 '17 at 09:07
  • 1
    You didn't flesh out your use cases for this question but one of them might be as follows: You want to AVOID getting a copy of a LARGE **UNCHANGED** file. Assume a local HASH of a large file and a local large file. Assume the server has a LARGE file and a current HASH for that file. You can download the **server HASH** and see if it matches the local HASH - if so, you don't have to get a new copy of the file. You can ALSO use the HASH and a local algorithm to sanity check the local LARGE file. – Steven the Easily Amused Jan 26 '21 at 00:16

12 Answers12

54

Unless you're using a really complicated and/or slow hash, loading the data from the disk is going to take much longer than computing the hash (unless you use RAM disks or top-end SSDs).

So to compare two files, use this algorithm:

  • Compare sizes
  • Compare dates (be careful here: this can give you the wrong answer; you must test whether this is the case for you or not)
  • Compare the hashes

This allows for a fast fail (if the sizes are different, you know that the files are different).

To make things even faster, you can compute the hash once and save it along with the file. Also save the file date and size into this extra file, so you know quickly when you have to recompute the hash or delete the hash file when the main file changes.

Aaron Digulla
  • 297,790
  • 101
  • 558
  • 777
  • 4
    I've implemented a working solution that uses alternate data streams under NTFS to store hashes. One thing I had to do, however, was to timestamp the hash so that I could tell if the file had been modified since it had last been hashed. – Steven Sudit Feb 03 '11 at 07:44
  • 2
    Fast disks today can read at 2.5GB per second. Hashes are nowhere near that fast in my experience. – Abhi Beckert Aug 26 '17 at 23:51
  • @AbhiBeckert My argument is: If you have the hashes computed, you don't need to load the whole data set. Also my first sentence is "Unless you're using a really complicated and/or slow hash", isn't it? – Aaron Digulla Sep 04 '17 at 09:39
  • @AaronDigulla in my case, I'm wanting to check if the contents of a large list of files still match their previously calculated hash, so it needs to be re-calculated. Using sha1 and a fast SSD and a large list of files, hash calculation is pinning all my CPU cores at 100% for an hour or two, causing fans to spin up to maximum speed and clock speed to be throttled to prevent overheating and so on and so on. I came here to find a more efficient hash. I don't think sha1 is complicated or slow as far as strong hashes go, although "really" is a relative term. I tried MD5 with similar results. – Abhi Beckert Sep 05 '17 at 04:18
  • 1
    @AbhiBeckert I see. SHA and MD were designed with crypto in mind (security is more important than speed). This questions might help: https://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed – Aaron Digulla Sep 25 '17 at 15:47
  • @AaronDigulla I'm aware of that. My point is that you should clarify your answer since it's currently wrong. Almost all hashes are designed for crypto and they can all be significantly slower than just reading the contents from disk and doing a direct comparison of every byte. Instead of "Unless you're using a really complicated/slow hash ..." your answer should say "if you use X, Y or Z fast hash ...". Also, many of those faster hash functions have unacceptably high collision risks for any file large enough to care about speed. Perhaps add a "compare contents" step where the hashes match. – Abhi Beckert Sep 28 '17 at 06:28
  • @AbhiBeckert When I wrote that answer, SSDs were rare and not that fast. Typically, your CPU cache was 100-1000 times faster than main memory and memory was 1000 times faster than loading data from hard disk. This has changed. That said, your use case is different from this question. Sending the data over the network is very, very slow. Even a very slow hash will outrun gigabit ethernet hands down. I suggest to ask a new question. – Aaron Digulla Sep 29 '17 at 15:32
30

One approach might be to use a simple CRC-32 algorithm, and only if the CRC values compare equal, rerun the hash with a SHA1 or something more robust. A fast CRC-32 will outperform a cryptographically secure hash any day.

Greg Hewgill
  • 828,234
  • 170
  • 1,097
  • 1,237
  • 12
    I'd say that hashing a file is likely to be I/O-bound anyhow, so you might as well use a hash with good distribution and a large range (certainly any crypto hash qualifies). – Steven Sudit Aug 12 '10 at 01:40
  • 24
    I'm going to contradict myself here: if there are just two files of equal length, you're not going to get any faster with hashes than by direct comparison. If you have a number of files and want to find candidates for equality, a hash makes sense. – Steven Sudit Feb 03 '11 at 07:39
  • 7
    If you're comparing files over a network (as the OP is), then reading each file amounts to re-transmitting the file over the network a second time. So using some sort of hashing probably makes sense. But I would agree with using a good hashing algorithm the first time, rather than doing a preliminary CRC32 followed by something else. – Flimzy Jan 20 '16 at 10:01
  • 3
    @StevenSudit it's not IO bound on a fast SSD. I've got a test file where md5 takes a minute but my SSD can read the file in just 25 seconds. And my SSD is a few years old, you can get faster ones now. – Abhi Beckert Aug 26 '17 at 22:51
  • 1
    Even if just comparing locally, if the only result needed is "equal" / "not equal", it probably still makes sense to hash, because that allows the drive/OS to read the file as fast as possible, instead of alternating chunks between 2 files. – hmijail mourns resignees Oct 21 '19 at 14:10
21

xxhash purports itself as quite fast and strong, collision-wise:

http://cyan4973.github.io/xxHash/

There is a 64 bit variant that runs "even faster" on 64 bit processors than the 32, overall, though slower on 32-bit processors (go figure).

http://code.google.com/p/crcutil is also said to be quite fast (and leverages hardware CRC instructions where present, which are probably very fast, but if you don't have hardware that supports them, aren't as fast). Don't know if CRC32c is as good of a hash (in terms of collisions) as xxHash or not...

https://code.google.com/p/cityhash/ seems similar and related to crcutil [in that it can compile down to use hardware CRC32c instructions if instructed].

If you "just want the fastest raw speed" and don't care as much about quality of random distribution of the hash output (for instance, with small sets, or where speed is paramount), there are some fast algorithms mentioned here: http://www.sanmayce.com/Fastest_Hash/ (these "not quite random" distribution type algorithms are, in some cases, "good enough" and very fast). Apparently FNV1A_Jesteress is the fastest for "long" strings, some others possibly for small strings. http://locklessinc.com/articles/fast_hash/ also seems related. I did not research to see what the collision properties of these are.

rogerdpack
  • 50,731
  • 31
  • 212
  • 332
  • 1
    "There is a 64 bit variant that runs "even faster" on 64 bit processors than the 32, overall, though slower on 32-bit processors (go figure)." - okay, I figure the 64bit code is optimized for 64bit processors and is using 64bit long integers for chunking the hashing mechanism. – Ben Personick May 17 '19 at 21:13
3

You could try MurmurHash, which was specifically designed to be fast, and is pretty simple to code. You might want to and a second, more secure hash if MurmurHash returns a match though, just to be sure.

int3
  • 12,011
  • 6
  • 47
  • 78
  • The OP stated that security was not a consideration here, so I'm not sure why a second hash would help. Instead, I'd suggest using one of the 64-bit variants of Murmur. – Steven Sudit Aug 12 '10 at 01:42
  • I'm going to contradict myself by suggesting that the newer 128-bit variant is better, and then contradict myself by adding that, for this use case, I'd stick with a proper crypto hash, such as SHA-256. – Steven Sudit Feb 03 '11 at 07:41
  • http://cbloomrants.blogspot.com/2010/08/08-21-10-adler32.html and http://www.strchr.com/hash_functions seem to imply that murmurhash is faster, of only slightly, than adler/crc32. It may all depend on implementation, for instance this sse version says it is a "fast" crc-like hash: http://cessu.blogspot.com/2008/11/hashing-with-sse2-revisited-or-my-hash.html – rogerdpack Jun 21 '12 at 17:56
3

For this type of application, Adler32 is probably the fastest algorithm, with a reasonable level of security. For bigger files, you may calculate multiple hash values, for example one per block of 5 Mb of the file, hence decreasing the chances of errors (i.e. of cases when the hashes are same yet the file content differ). Furthermore this multi-hash values setup may allow the calculation of the hash to be implemented in a multi-thread fashion.

Edit: (Following Steven Sudit's remark)
A word of caution if the files are small!
Adler32's "cryptographic" properties, or rather its weaknesses are well known particularly for short messages. For this reason the solution proposed should be avoided for files smaller than than a few kilobytes.
Never the less, in the question, the OP explicitly seeks a fast algorithm and waives concerns about security. Furthermore the quest for speed may plausibly imply that one is dealing with "big" files rather than small ones. In this context, Adler32, possibly applied in parallel for files chunks of say 5Mb remains a very valid answer. Alder32 is reputed for its simplicity and speed. Also, its reliability, while remaining lower than that of CRCs of the same length, is quite acceptable for messages over 4000 bytes.

mjv
  • 67,473
  • 12
  • 100
  • 152
  • I would not recommend Adler32 for any purpose. It has terrible characteristics, particularly for short files. – Steven Sudit Aug 12 '10 at 01:43
  • There are faster algorithms that are nonetheless much better. MurmurHash3 comes to mind, but for this use case, I'd suggest that I/O speed is the limit so SHA-256 would be good. – Steven Sudit Feb 03 '11 at 07:42
  • (Also, please use the comment option instead of editing your remark, else I'll only know about your response if I get lucky.) – Steven Sudit Feb 03 '11 at 07:43
  • apparently adler32 is "bad for numbers" http://www.strchr.com/hash_functions but CRC32 is ok, at least distribution wise. – rogerdpack Jun 21 '12 at 17:50
3

What we are optimizing here is time spent on a task. Unfortunately we do not know enough about the task at hand to know what the optimal solution should be.

Is it for one-time comparison of 2 arbitrary files? Then compare size, and after that simply compare the files, byte by byte (or mb by mb) if that's better for your IO.

If it is for 2 large sets of files, or many sets of files, and it is not a one-time exercise. but something that will happen frequently, then one should store hashes for each file. A hash is never unique, but a hash with a number of say 9 digits (32 bits) would be good for about 4 billion combination, and a 64 bit number would be good enough to distinguish between some 16 * 10^18 Quintillion different files.

A decent compromise would be to generate 2 32-bit hashes for each file, one for first 8k, another for 1MB+8k, slap them together as a single 64 bit number. Cataloging all existing files into a DB should be fairly quick, and looking up a candidate file against this DB should also be very quick. Once there is a match, the only way to determine if they are the same is to compare the whole files.

I am a believer in giving people what they need, which is not always never what they think they need, or what the want.

bjorn
  • 31
  • 1
2

In any case, you should read each file fully (except case when sizes mismatch), so just read both file and compare block-to-block.

Using hash just gain CPU usage and nothing more. As you do not write anything, cache of OS will effectively DROP data you read, so, under Linux, just use cmp tool

socketpair
  • 1,804
  • 15
  • 14
2

If it's only a one off then given that you'll have to read both files to generate a hash of both of them, why not just read through a small amount of each at a time and compare?

Failing that CRC is a very simple algorithm.

Jeff Foster
  • 40,078
  • 10
  • 78
  • 103
  • +1 for CRC, since the OP asked for "fastest". Of course, then he asked for "making sure the files are the same" which contradicts itself LOL. – rogerdpack Jun 21 '12 at 17:27
  • @rogerdpack crc isn't close to fastest hash, even with asm. – OneOfOne Aug 14 '14 at 00:00
  • 1
    @OneOfOne true I believe I didn't realize that at the time. These days I recommend xxhash or cityhash, see my other answer here http://stackoverflow.com/a/11422479/32453 [apparently with crc32c it can compile down to a CPU instruction which is very fast...though that's not what I was referring to initially here I don't think so your comment is right] – rogerdpack Aug 15 '14 at 16:05
1

The following is the code to find duplicate files from my personal project to sort pictures which also removes duplicates. As per my experience, first using fast hashing algo like CRC32 and then doing MD5 or SHA1 was even slower and didn't made any improvement as most of the files with same sizes were indeed duplicate so running hashing twice was more expensive from cpu time perspective, this approach may not be correct for all type of projects but it definitely true for image files. Here I am doing MD5 or SHA1 hashing only on the files with same size.

PS: It depends on Apache commons codec to generate hash efficiently.

Sample usage: new DuplicateFileFinder("MD5").findDuplicateFilesList(filesList);

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;

    import org.apache.commons.codec.digest.DigestUtils;

    /**
     * Finds the duplicate files using md5/sha1 hashing, which is used only for the sizes which are of same size.
     *  
     * @author HemantSingh
     *
     */
    public class DuplicateFileFinder {

        private HashProvider hashProvider;
        // Used only for logging purpose.
        private String hashingAlgo;

        public DuplicateFileFinder(String hashingAlgo) {
            this.hashingAlgo = hashingAlgo;
            if ("SHA1".equalsIgnoreCase(hashingAlgo)) {
                hashProvider = new Sha1HashProvider();
            } else if ("MD5".equalsIgnoreCase(hashingAlgo)) {
                hashProvider = new Md5HashProvider();
            } else {
                throw new RuntimeException("Unsupported hashing algorithm:" + hashingAlgo + " Please use either SHA1 or MD5.");
            }
        }

        /**
         * This API returns the list of duplicate files reference.
         * 
         * @param files
         *            - List of all the files which we need to check for duplicates.
         * @return It returns the list which contains list of duplicate files for
         *         e.g. if a file a.JPG have 3 copies then first element in the list
         *         will be list with three references of File reference.
         */
        public List<List<File>> findDuplicateFilesList(List<File> files) {
            // First create the map for the file size and file reference in the array list.
            Map<Long, List<File>> fileSizeMap = new HashMap<Long, List<File>>();
            List<Long> potDuplicateFilesSize = new ArrayList<Long>();

            for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                Long fileLength = new Long(file.length());
                List<File> filesOfSameLength = fileSizeMap.get(fileLength);
                if (filesOfSameLength == null) {
                    filesOfSameLength = new ArrayList<File>();
                    fileSizeMap.put(fileLength, filesOfSameLength);
                } else {
                    potDuplicateFilesSize.add(fileLength);
                }
                filesOfSameLength.add(file);
            }

            // If we don't have any potential duplicates then skip further processing.
            if (potDuplicateFilesSize.size() == 0) {
                return null;
            }

            System.out.println(potDuplicateFilesSize.size() + " files will go thru " + hashingAlgo + " hash check to verify if they are duplicate.");

            // Now we will scan the potential duplicate files, and eliminate false positives using md5 hash check.
            List<List<File>> finalListOfDuplicates = new ArrayList<List<File>>();
            for (Iterator<Long> potDuplicatesFileSizeIterator = potDuplicateFilesSize
                    .iterator(); potDuplicatesFileSizeIterator.hasNext();) {
                Long fileSize = (Long) potDuplicatesFileSizeIterator.next();
                List<File> potDupFiles = fileSizeMap.get(fileSize);
                Map<String, List<File>> trueDuplicateFiles = new HashMap<String, List<File>>();
                for (Iterator<File> potDuplicateFilesIterator = potDupFiles.iterator(); potDuplicateFilesIterator
                        .hasNext();) {
                    File file = (File) potDuplicateFilesIterator.next();
                    try {
                        String md5Hex = hashProvider.getHashHex(file);
                        List<File> listOfDuplicatesOfAFile = trueDuplicateFiles.get(md5Hex);
                        if (listOfDuplicatesOfAFile == null) {
                            listOfDuplicatesOfAFile = new ArrayList<File>();
                            trueDuplicateFiles.put(md5Hex, listOfDuplicatesOfAFile);
                        }
                        listOfDuplicatesOfAFile.add(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Collection<List<File>> dupsOfSameSizeList = trueDuplicateFiles.values();
                for (Iterator<List<File>> dupsOfSameSizeListIterator = dupsOfSameSizeList.iterator(); dupsOfSameSizeListIterator
                        .hasNext();) {
                    List<File> list = (List<File>) dupsOfSameSizeListIterator.next();
                    // It will be duplicate only if we have more then one copy of it.
                    if (list.size() > 1) {
                        finalListOfDuplicates.add(list);
                        System.out.println("Duplicate sets found: " + finalListOfDuplicates.size());
                    }
                }
            }

            return finalListOfDuplicates;
        }

        abstract class HashProvider {
            abstract String getHashHex(File file) throws IOException ;
        }

        class Md5HashProvider extends HashProvider {
            String getHashHex(File file) throws IOException {
                return DigestUtils.md5Hex(new FileInputStream(file));
            }
        }
        class Sha1HashProvider extends HashProvider {
            String getHashHex(File file) throws IOException {
                return DigestUtils.sha1Hex(new FileInputStream(file));
            }
        }
    }
Hemant
  • 4,317
  • 8
  • 37
  • 41
1

Why do you want to hash it?

If you want to make sure that two files are equal then by definition you will have to read the entire file (unless they are literally the same file, in which case you can tell by looking at meta-data on the file system). Anyways, no reason to hash, just read over them and see if they are the same. Hashing will make it less efficient. And even if the hashes match, you still aren't sure if the files really are equal.

Edit: This answer was posted before the question specified anything about a network. It just asked about comparing two files. Now that I know there is a network hop between the files, I would say just use an MD5 hash and be done with it.

tster
  • 16,762
  • 5
  • 49
  • 70
  • 4
    I am sending a file over a network connection, and will be sure that the file on both sides are equal. – eflles Nov 19 '09 at 07:59
  • 3
    Oh, well in that case just use a real hash algorithm. I guarantee your network will be slower than the hash. – Greg Hewgill Nov 19 '09 at 08:01
  • In such a case, use an already existing hash function. Greg, posted some good examples. – tster Nov 19 '09 at 08:01
1

you might check out the algorithm that the samba/rsync developers use. I haven't looked at it in depth, but i see it mentioned all the time. apparently its quite good.

clarson
  • 545
  • 1
  • 6
  • 15
  • rsync is actually using a "rolling checksum" version of the Adler32 algorithm, as of Wikipedia: https://en.wikipedia.org/wiki/Adler-32 – Bigue Nique Jun 16 '14 at 12:28
0

I remember the old modem transfer protocols, like Zmodem, would do some sort of CRC compare for each block as it was sent. CRC32, if I remember ancient history well enough. I'm not suggesting you make your own transfer protocol, unless that's exactly what you're doing, but you could maybe have it spot check a block of the file periodically, or maybe doing hashes of each 8k block would be simple enough for the processors to handle. Haven't tried it, myself.

Ricochetv1
  • 11
  • 1