Confirm file contents against hash

I have a requirement to "check the integrity" of the contents of files. Files will be written to CD / DVD, which can be copied many times. The idea is to identify copies (after they were deleted from Nero, etc.) that were copied correctly.

I'm new to this, but a quick search suggests it Arrays.hashCode(byte[])will fit the needs. We can include a file on the disk containing the result of this call for each resource of interest, and then compare it with byte[] Filehow it was read from the disk, if it is installed.

Do I understand the method correctly, is this the right way to check the contents of a file?

If not, suggestions for finding keywords or strategies / methods / classes will be appreciated.


Working code based on Brendan's answer. It takes care of the problem identified by VoidStar (a whole memory is required to store the hash byte[]).

import java.io.File;
import java.io.FileInputStream;
import java.util.zip.CRC32;

class TestHash {

    public static void main(String[] args) throws Exception {
        File f = new File("TestHash.java");
        FileInputStream fis = new FileInputStream(f);
        CRC32 crcMaker = new CRC32();
        byte[] buffer = new byte[65536];
        int bytesRead;
        while((bytesRead = fis.read(buffer)) != -1) {
            crcMaker.update(buffer, 0, bytesRead);
        }
        long crc = crcMaker.getValue(); // This is your error checking code
        System.out.println("CRC code is " + crc);
    }
}
+5
source share
3 answers

Arrays.hashCode()designed very fast (used in hash tables). I highly recommend not using it for this purpose.

What you want is some kind of error checking code like CRC .

Java has a class for calculating them: CRC32 :

InputStream in = ...;
CRC32 crcMaker = new CRC32();
byte[] buffer = new byte[someSize];
int bytesRead;
while((bytesRead = in.read(buffer)) != -1) {
    crcMaker.update(buffer, 0, bytesRead);
}
long crc = crcMaker.getValue(); // This is your error checking code
+8
source

, , , , . , , . , , . , , , , -, , .

+1

Here is an example:

You need to create a checksum file
http://www.jguru.com/faq/view.jsp?EID=216274

+1
source

All Articles