BouncyDigest.java

/*******************************************************************************
 * GordianKnot: Security Suite
 * Copyright 2012,2025 Tony Washer
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package net.sourceforge.joceanus.gordianknot.impl.bc;

import org.bouncycastle.crypto.Digest;

import net.sourceforge.joceanus.gordianknot.api.digest.GordianDigestSpec;
import net.sourceforge.joceanus.gordianknot.impl.core.digest.GordianCoreDigest;

/**
 * BouncyCastle Digest.
 */
public class BouncyDigest
        extends GordianCoreDigest {
    /**
     * Digest.
     */
    private final Digest theDigest;

    /**
     * Constructor.
     * @param pDigestSpec the digestSpec
     * @param pDigest the digest
     */
    BouncyDigest(final GordianDigestSpec pDigestSpec,
                 final Digest pDigest) {
        super(pDigestSpec);
        theDigest = pDigest;
    }

    /**
     * Obtain Underlying Digest.
     * @return the underlying digest
     */
    Digest getDigest() {
        return theDigest;
    }

    @Override
    public int getDigestSize() {
        return getDigestSpec() != null
               ? super.getDigestSize()
               : theDigest.getDigestSize();
    }

    @Override
    public void doUpdate(final byte[] pBytes,
                         final int pOffset,
                         final int pLength) {
        theDigest.update(pBytes, pOffset, pLength);
    }

    @Override
    public void update(final byte pByte) {
        theDigest.update(pByte);
    }

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

    @Override
    public byte[] finish() {
        final byte[] myResult = new byte[getDigestSize()];
        doFinish(myResult, 0);
        return myResult;
    }

    @Override
    public int doFinish(final byte[] pBuffer,
                        final int pOffset) {
        return theDigest.doFinal(pBuffer, pOffset);
    }
}