
package fortuna.generator;

/**
 *
 * @author Viliam Krizan
 */

import aalg.crypto.ByteArraySymmetricKey;
import aalg.crypto.IBlockCipher;
import aalg.crypto.IBlockCipherTransformation;
import aalg.crypto.ISymmetricKey;


public class BlockCipherGenerator implements IGenerator{
    
    private final IBlockCipher cipher;
    private final IBlockCipherTransformation encryptor;
    private final Counter counter;
    private ISymmetricKey key;
    
    public BlockCipherGenerator(final IBlockCipher cipher){
        int counterSize = cipher.getBlockLength();
        
        byte[] keyBytes = new byte[32];
        for (int i = 1; i < 32; i++) {
            keyBytes[i]=(byte)0;
        }
        key = new ByteArraySymmetricKey(keyBytes);
        counter = new Counter(counterSize);
        this.cipher = cipher;
        this.encryptor =  cipher.getEncryptor();
        encryptor.setKey(key);
    }
    
    @Override
    public void setKey(ISymmetricKey key){
        encryptor.setKey(key);
    }
        
    
    @Override
    public void generate(byte[] result){
        final int blockLength = encryptor.getCipher().getBlockLength();
        byte[] block = new byte[blockLength];
        int offset = 0;
        
        while(offset<result.length){
            encryptor.transformBlock(counter.getCounter(), 0, block, 0);
            counter.incrementCounter(0);
            
            final int size = Math.min(result.length-offset, blockLength);
            System.arraycopy(block, 0, result, offset, size);
            offset += size;
        }
    }
}
