Ale*_*lex 14 java checksum object
我正在寻找一种解决方案来为任何类型的Java对象生成校验和,对于生成相同对象的应用程序的每次执行,它都保持不变.
我试过了Object.hashCode(),但是api说
....从应用程序的一次执行到同一应用程序的另一次执行,这个整数不需要保持一致.
Leo*_*tão 13
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我有类似的问题(为XML文件生成良好的哈希码),我发现最好的解决方案是通过MessageDigest使用MD5,或者如果你需要更快的东西:快速MD5.请注意,即使Object.hashCode每次它都太短(仅32位)以确保高唯一性,它们也是相同的.我认为64位是计算良好哈希码的最小值.请注意,MD5生成128位长的哈希码,在这种情况下应该更加需要.
当然要使用MessageDigest你需要首先序列化(在你的情况下是marshall)对象.
小智 8
例
private BigInteger checksum(Object obj) throws IOException, NoSuchAlgorithmException {
if (obj == null) {
return BigInteger.ZERO;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
MessageDigest m = MessageDigest.getInstance("SHA1");
m.update(baos.toByteArray());
return new BigInteger(1, m.digest());
}