How to generate a checksum for an java object

I had similar problem (generating good hashcode for XML files) and I found out that the best solution is to use MD5 through MessageDigest or in case you need something faster: Fast MD5. Please notice that even if Object.hashCode would be the same every time it is anyway too short (only 32 bits) to ensure high uniqueness. I think 64 bits is a minimum to compute good hash code. Please be aware that MD5 generates 128 bits long hash code, which should is even more that needed in this situation.

Of course to use MessageDigest you need serialize (in your case marshall) the object first.


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