package aalgTest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import aalg.crypto.AesCipher;
import aalg.crypto.ByteArraySymmetricKey;
import aalg.crypto.CbcStreamCipher;
import aalg.crypto.CtrStreamCipher;
import aalg.crypto.IBlockCipher;
import aalg.crypto.IInputStreamFilter;
import aalg.crypto.IOutputStreamFilter;
import aalg.crypto.IPadding;
import aalg.crypto.IStreamDecryptor;
import aalg.crypto.IStreamEncryptor;
import aalg.crypto.ISymmetricStreamDecryptor;
import aalg.crypto.ISymmetricStreamEncryptor;
import aalg.crypto.Pkcs7Padding;
import aalg.crypto.TestRandomGenerator;

public class CtrStreamCipherTest extends PipeTest {
	
	private final TestRandomGenerator rng;
	private final ByteArraySymmetricKey key;
	private final IBlockCipher blockCipher;
	private final CtrStreamCipher cipher;

	public CtrStreamCipherTest() {
		rng = new TestRandomGenerator();

		blockCipher = new AesCipher(AesCipher.AES_128_KEY_SIZE);
		cipher = new CtrStreamCipher(blockCipher, blockCipher, rng);

		final byte[] keyBytes = new byte[cipher.getKeySize()];
		rng.fillArray(keyBytes, 0, keyBytes.length);
		
		key = new ByteArraySymmetricKey(keyBytes);
	}
	
	@Override
	protected IInputStreamFilter getInputFilter(final ByteArrayInputStream inputStream) throws IOException {
		final ISymmetricStreamDecryptor decryptor = cipher.getDecryptor();
		decryptor.setKey(key);
		decryptor.initialize(inputStream);
		
		return decryptor;
	}

	@Override
	protected void flushInputFilter(final IInputStreamFilter filter) throws IOException {
		((IStreamDecryptor) filter).finish();
	}

	@Override
	protected IOutputStreamFilter getOutputFilter(final ByteArrayOutputStream outputStream) throws IOException {
		final ISymmetricStreamEncryptor encryptor = cipher.getEncryptor();
		encryptor.setKey(key);
		encryptor.initialize(outputStream);
		
		return encryptor;
	}

	@Override
	protected void flushOutputFilter(final IOutputStreamFilter filter) throws IOException {
		((IStreamEncryptor) filter).finish();
	}

}
