How to generate a checksum for an java object

后端 未结 10 807
生来不讨喜
生来不讨喜 2020-12-13 01:04

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.

10条回答
  •  庸人自扰
    2020-12-13 01:36

    Example

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

提交回复
热议问题