// 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 java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    private static void crypt(int mode, String fromname, String toname, String key) throws Exception {
        Cipher aes = Cipher.getInstance("AES");
        aes.init(mode, new SecretKeySpec(key.getBytes("UTF-8"), "AES"));
        InputStream is = new FileInputStream(fromname);
        OutputStream os = new FileOutputStream(toname);
        byte[] b = new byte[10000];
        int n;
        while((n = is.read(b)) >= 0) {
            byte[] b2;
            if(n < b.length) {
                b2 = aes.doFinal(b, 0, n);
            } else {
                b2 = aes.update(b, 0, n);
            }
            os.write(b2, 0, b2.length);   
            System.out.println(n + " " + b2.length);
        }
        is.close();
        os.close();
    }
    public static void encrypt(String fromname, String toname, String key) throws Exception {
        crypt(Cipher.ENCRYPT_MODE, fromname, toname, key);
    }
    public static void decrypt(String fromname, String toname, String key) throws Exception {
        crypt(Cipher.DECRYPT_MODE, fromname, toname, key);
    }
    public static void main(String[] args) throws Exception {
        encrypt("C:\\z.1", "C:\\z.2", "Top hemmelig key");
        decrypt("C:\\z.2", "C:\\z.3", "Top hemmelig key");
    }
}
