package com.jscape.crypto;

import java.security.MessageDigest;
import java.security.Provider;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class JceHash
        implements Hash {

    private final MessageDigest base;

    public static JceHash hashFor(String name, String provider)
            throws Exception {
        MessageDigest base = provider != null ? MessageDigest.getInstance(name, provider) : MessageDigest.getInstance(name);
        return new JceHash(base);
    }

    public static JceHash hashFor(String name, Provider provider)
            throws Exception {
        MessageDigest base = provider != null ? MessageDigest.getInstance(name, provider) : MessageDigest.getInstance(name);
        return new JceHash(base);
    }

    public JceHash(MessageDigest base) {
        assertNotNull(base);
        this.base = base;
    }

    @Override
    public int getLength() {
        return this.base.getDigestLength();
    }

    @Override
    public Hash reset() {
        this.base.reset();
        return this;
    }

    @Override
    public Hash update(byte data) {
        this.base.update(data);
        return this;
    }

    @Override
    public Hash update(byte[] data) {
        this.base.update(data);
        return this;
    }

    @Override
    public Hash update(byte[] data, int offset, int length) {
        this.base.update(data, offset, length);
        return this;
    }

    @Override
    public byte[] compute() {
        return this.base.digest();
    }

    @Override
    public byte[] compute(byte[] data) {
        return this.base.digest(data);
    }

    @Override
    public byte[] compute(byte[] data, int offset, int length) {
        update(data, offset, length);
        return this.base.digest();
    }

    @Override
    public String toString() {
        return "JceHash {"
                + "base=" + this.base.getAlgorithm()
                + '}';
    }
}
