package org.cryptonit.cloud.timestamping;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.*;
import org.bouncycastle.operator.DigestCalculator;

/**
 * @author Mathias Brossard
 */
public class GenericDigestCalculator implements DigestCalculator {

    private ASN1ObjectIdentifier algo;
    private ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    public GenericDigestCalculator(ASN1ObjectIdentifier algo) {
        this.algo = algo;
    }

    @Override
    public AlgorithmIdentifier getAlgorithmIdentifier() {
        return new AlgorithmIdentifier(this.algo);
    }

    @Override
    public OutputStream getOutputStream() {
        return bOut;
    }

    @Override
    public byte[] getDigest() {
        byte[] bytes = bOut.toByteArray();
        bOut.reset();

        Digest d;
        if (this.algo.equals(OIWObjectIdentifiers.idSHA1)) {
            d = new SHA1Digest();
        } else if (this.algo.equals(NISTObjectIdentifiers.id_sha256)) {
            d = new SHA256Digest();
        } else if (this.algo.equals(NISTObjectIdentifiers.id_sha384)) {
            d = new SHA384Digest();
        } else if (this.algo.equals(NISTObjectIdentifiers.id_sha512)) {
            d = new SHA512Digest();
        } else {
            return null;
        }
        d.update(bytes, 0, bytes.length);
        byte[] digest = new byte[d.getDigestSize()];
        d.doFinal(digest, 0);
        return digest;
    }
}

@@ -557,17 +557,16 @@
 lator %7B%0A
-%0A
     priv
@@ -635,41 +635,11 @@
 am b
-Out = new ByteArrayOutputStream()
+aos
 ;%0A%0A 
@@ -723,24 +723,73 @@
 lgo = algo;%0A
+        this.baos = new ByteArrayOutputStream();%0A
     %7D%0A%0A    @
@@ -987,19 +987,19 @@
 return b
-Out
+aos
 ;%0A    %7D%0A
@@ -1049,74 +1049,8 @@
 ) %7B%0A
-        byte%5B%5D bytes = bOut.toByteArray();%0A        bOut.reset();%0A%0A
     
@@ -1063,16 +1063,17 @@
 gest d;%0A
+%0A
         
@@ -1535,24 +1535,25 @@
       %7D%0A
+%0A
         
 d.update
@@ -1548,39 +1548,40 @@
     
-d.update(bytes, 0, bytes.length
+byte%5B%5D bytes = baos.toByteArray(
 );%0A 
@@ -1632,16 +1632,80 @@
 ize()%5D;%0A
+        baos.reset();%0A        d.update(bytes, 0, bytes.length);%0A
         

Rename ByteArrayOutputStream and delay initializations