// 
// Decompiled by Procyon v0.6.0
// 

package org.bouncycastle.crypto.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.crypto.CryptoServicesRegistrar;
import java.security.SecureRandom;

public class JournalingSecureRandom extends SecureRandom
{
    private static byte[] EMPTY_TRANSCRIPT;
    private final SecureRandom base;
    private TranscriptStream tOut;
    private byte[] transcript;
    private int index;
    
    public JournalingSecureRandom() {
        this(CryptoServicesRegistrar.getSecureRandom());
    }
    
    public JournalingSecureRandom(final SecureRandom base) {
        this.tOut = new TranscriptStream();
        this.index = 0;
        this.base = base;
        this.transcript = JournalingSecureRandom.EMPTY_TRANSCRIPT;
    }
    
    public JournalingSecureRandom(final byte[] array, final SecureRandom base) {
        this.tOut = new TranscriptStream();
        this.index = 0;
        this.base = base;
        this.transcript = Arrays.clone(array);
    }
    
    @Override
    public final void nextBytes(final byte[] array) {
        if (this.index >= this.transcript.length) {
            this.base.nextBytes(array);
        }
        else {
            int n;
            for (n = 0; n != array.length && this.index < this.transcript.length; ++n) {
                array[n] = this.transcript[this.index++];
            }
            if (n != array.length) {
                final byte[] bytes = new byte[array.length - n];
                this.base.nextBytes(bytes);
                System.arraycopy(bytes, 0, array, n, bytes.length);
            }
        }
        try {
            this.tOut.write(array);
        }
        catch (final IOException ex) {
            throw new IllegalStateException("unable to record transcript: " + ex.getMessage());
        }
    }
    
    public void clear() {
        Arrays.fill(this.transcript, (byte)0);
        this.tOut.clear();
    }
    
    public void reset() {
        this.index = 0;
        if (this.index == this.transcript.length) {
            this.transcript = this.tOut.toByteArray();
        }
        this.tOut.reset();
    }
    
    public byte[] getTranscript() {
        return this.tOut.toByteArray();
    }
    
    public byte[] getFullTranscript() {
        if (this.index == this.transcript.length) {
            return this.tOut.toByteArray();
        }
        return Arrays.clone(this.transcript);
    }
    
    static {
        JournalingSecureRandom.EMPTY_TRANSCRIPT = new byte[0];
    }
    
    private static class TranscriptStream extends ByteArrayOutputStream
    {
        public void clear() {
            Arrays.fill(this.buf, (byte)0);
        }
    }
}
