MJar MJar - 3 months ago 22
Java Question

How can I save MessageDigest internal state into database?

Is it possible, and if than how, to save the internal state of MessageDigest object? I want to save it in a database, so have to use only primitive data like

String
,
int
,
byte[]
.

What I'm trying to achieve is to be able to receive a fragmented file (during a long period of time), save all the fragments in database, and after receiving last fragment verify the SHA512 digest of the file without getting back all the data previously saved in database.

So basically I want something like this:

MessageDigest md = MessageDigest.getInstance("SHA-512");
// restore previous internal state of md
md.update(dataSegment);
// save internal md state

Answer

you could serialize the object to String (XML format) and return it back.

check: http://x-stream.github.io/tutorial.html

public class DigestTest {

    private static final byte[] TEST_DATA = "Some test data for digest computations".getBytes();

    @Test
    public void shouldStoreAndRestoreDigest() throws Exception {
        final MessageDigest referenceDigest = MessageDigest.getInstance("SHA-512");
        MessageDigest testDigest = MessageDigest.getInstance("SHA-512");
        referenceDigest.update(TEST_DATA);
        testDigest.update(TEST_DATA);
        // store state
        final XStream xs = new XStream(new StaxDriver());
        xs.alias("md", MessageDigest.class);
        final String serializedMd = xs.toXML(testDigest);
        System.out.println(serializedMd);
        // restore state
        testDigest = (MessageDigest)xs.fromXML(serializedMd);
        // ---
        referenceDigest.update(TEST_DATA);
        testDigest.update(TEST_DATA);
        Assert.assertArrayEquals(referenceDigest.digest(), testDigest.digest());
    }
}