散列整个对象而不首先转换为byte []

时间:2018-04-20 21:08:43

标签: java hash sha256

我想得到特定java对象的sha2哈希值。我不希望它是int,我想要byte[]或至少String。我有以下代码来创建sha2:

static byte[] sha2(byte[] message) {
    if (message == null || message.length == 0) {
        throw new IllegalArgumentException("message is null");
    }
    try {
        MessageDigest sha256 = MessageDigest.getInstance(SHA_256);
        return sha256.digest(message);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    }
}

我可以将我的对象转换为byte[],但我不认为将大数组存储在内存中只是为了创建32字节数组。那么如何计算对象的sha2(或者可能是另一个加密哈希函数)呢?

1 个答案:

答案 0 :(得分:3)

You do not have to load the whole object into memory, you can load parts of it into temporary buffer.

Dump object into a temporary file using FileOutputStream/BufferedOutputStream, this will make sure serialized object does not pollute JVM memory.

The load serialize object from temporary file using FileInputStream/BufferedInputStream and feed it to MessageDigest#update(buf) method in a loop.

Finally call MessageDigest#digest() to finish work:

int[] buf = new int[1024];
while (/* has more data */) {
    int readBytes = readIntoBuf(buf);
    sha256.update(buf, 0, readBytes);
}
return sha256.digest();

If you can afford to store entire serialized object in memory, use ByteArrayOutputStream and pass result byte[] to MessageDigest#digest(buf):

try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOuputStream(baos)) {
    oos.writeObject(obj);

    MessageDigest sha256 = MessageDigest.getInstance(SHA_256);
    return sha256.digest(baos.toByteArray());
}