package aalg.crypto;

import java.io.IOException;
import java.io.OutputStream;

public class CtrStreamEncryptor extends CtrStreamBase implements ISymmetricStreamEncryptor {

	private final IRandomGenerator rng;
	private OutputStream cipherTextStream;
	
	private final OutputStream plainTextStream = new OutputStream() {
		@Override
		public void write (final int b) throws IOException {			
			final int cipherText = b ^ getKeyStreamByte();
			
			cipherTextStream.write(cipherText);
		}		
	};

	public CtrStreamEncryptor(final IBlockCipher dataBlockCipher, final IBlockCipher ivBlockCipher, final IRandomGenerator rng, final int[] increment) {
		super(dataBlockCipher, ivBlockCipher, increment);
		
		this.rng = rng;
	}

	@Override
	public void initialize(final OutputStream cipherTextStream) throws IOException {
		this.cipherTextStream = cipherTextStream;
		
		final byte[] nonce = new byte[blockLength];
		rng.fillArray(nonce, 0, blockLength);
		
		cipherTextStream.write(nonce);
		
		initializeCounter (nonce);
	}

	@Override
	public void finish() throws IOException {
	}

	@Override
	public OutputStream getSourceStream() throws IOException {
		return plainTextStream;
	}

	@Override
	public OutputStream getTargetStream() throws IOException {
		return cipherTextStream;
	}

}
