// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CipherPooling {
    private static final String key = "Top hemmelig key";
    private static final String data = "Top hemmelige data";
    private static final byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    private static Cipher aes2 = null;
    public static void test1() throws Exception {
        Cipher aes1 = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aes1.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("UTF-8"), "AES"), new IvParameterSpec(iv));
        byte[] plain = data.getBytes("UTF-8");
        byte[] cipher = aes1.doFinal(plain, 0, plain.length);
        if(cipher[0] != -13) {
            throw new RuntimeException("Ooops");
        }
    }
    public static void test2() throws Exception {
        if(aes2 == null) {
            aes2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }
        aes2.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("UTF-8"), "AES"), new IvParameterSpec(iv));
        byte[] plain = data.getBytes("UTF-8");
        byte[] cipher = aes2.doFinal(plain, 0, plain.length);
        if(cipher[0] != -13) {
            throw new RuntimeException("Ooops");
        }
    }
    private static final int N = 1000000;
    public static void main(String[] args) throws Exception {
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            test1();
        }
        long t2 = System.currentTimeMillis();
        System.out.println("not reuse: " + (t2 - t1));
        long t3 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            test2();
        }
        long t4 = System.currentTimeMillis();
        System.out.println("reuse: " + (t4 - t3));
    }
}
