package aalg.crypto;

import java.io.IOException;
import java.io.InputStream;
import aalg.algebra.Utils;

public class CtrStreamDecryptor extends CtrStreamBase implements ISymmetricStreamDecryptor {
	
	private InputStream cipherTextStream;
	
	private final InputStream plainTextStream = new InputStream() {
		@Override
		public int read() throws IOException {			
			final int cipherText = cipherTextStream.read();
			
			if (cipherText < 0)
				return cipherText;
			
			return (cipherText ^ getKeyStreamByte()) & 0xFF;
		}		
	};

	public CtrStreamDecryptor(final IBlockCipher dataBlockCipher, final IBlockCipher ivBlockCipher, final int[] increment) {
		super(dataBlockCipher, ivBlockCipher, increment);
	}

	@Override
	public void initialize(final InputStream cipherTextStream) throws IOException {
		this.cipherTextStream = cipherTextStream;
		
		final byte[] nonce = new byte[blockLength];
		Utils.readByteArray(cipherTextStream, nonce, 0, blockLength);
		
		initializeCounter(nonce);
	}

	@Override
	public void finish() {
	}

	@Override
	public InputStream getTargetStream() throws IOException {
		return plainTextStream;
	}

	@Override
	public InputStream getSourceStream() throws IOException {
		return cipherTextStream;
	}

}
