MJar MJar - 1 year ago 79
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


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
// save internal md state

Answer Source

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

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