/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.cksum;

import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Implementation of the <code>Checksum</code> interface resting on the Java 7 Security API.
 *
 * @author Alex Leigh
 */
public class MessageDigestChecksum implements Checksum {
    private final MessageDigest mDigest;

    public MessageDigestChecksum(String algorithm) throws NoSuchAlgorithmException {
        mDigest = MessageDigest.getInstance(algorithm);
    }

    @Override
    public int getSize() {
        return mDigest.getDigestLength();
    }

    @Override
    public void update(byte[] data) {
        mDigest.digest(data);
    }

    @Override
    public ByteBuffer getChecksumValue() {
        ByteBuffer b = ByteBuffer.allocate(getSize());
        writeChecksumValue(b);
        return b;
    }

    @Override
    public void writeChecksumValue(ByteBuffer data) {
        byte[] ck = mDigest.digest();
        data.put(ck);
    }

    @Override
    public void reset() {
        mDigest.reset();
    }
}
