Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a checksum for an java object

Tags:

I'm looking for a solution to generate a checksum for any type of Java object, which remains the same for every execution of an application that produces the same object.

I tried it with Object.hashCode(), but the api says

....This integer need not remain consistent from one execution of an application to another execution of the same application.

like image 653
Alex Avatar asked Apr 15 '10 11:04

Alex


People also ask

What is checksum in Java?

Essentially, a checksum is a minified representation of a binary stream of data. Checksums are commonly used for network programming in order to check that a complete message has been received.

How do I find the checksum of a jar file?

If you are building the jar file with maven there is a maven plug-in for generating check-sums of a compiled jar. Maven Plugin Link . As for the downloaded jar you can locally SAVE ,rather than generate, the jars check sum.


1 Answers

public static String getChecksum(Serializable object) throws IOException, NoSuchAlgorithmException {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(baos.toByteArray());
        return DatatypeConverter.printHexBinary(thedigest);
    } finally {
        oos.close();
        baos.close();
    }
}
like image 194
Leonardo Leitão Avatar answered Sep 18 '22 15:09

Leonardo Leitão