// 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.*;

import javax.mail.internet.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class BlowFish {
    private Cipher bf;
    private SecretKey bfkey;
    public BlowFish(byte[] key) {
        try {
            bf = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
            bfkey = new SecretKeySpec(key, "Blowfish");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    private byte[] encrypt(byte[] plaindata) throws Exception {
        bf.init(Cipher.ENCRYPT_MODE, bfkey);
        return bf.doFinal(plaindata);
    }
    private byte[] decrypt(byte[] cipherdata) throws Exception {
        bf.init(Cipher.DECRYPT_MODE, bfkey);
        return bf.doFinal(cipherdata);
    }
    public static byte[] b64encode(byte[] b) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream b64os = MimeUtility.encode(baos, "base64");
        b64os.write(b);
        b64os.close();
        return baos.toByteArray();
     }
     public static byte[] b64decode(byte[] b) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        InputStream b64is = MimeUtility.decode(bais, "Base64");
        byte[] tmp = new byte[b.length];
        int n = b64is.read(tmp);
        byte[] res = new byte[n];
        System.arraycopy(tmp, 0, res, 0, n);
        return res;
    }
    public static void main(String[] args) throws Exception {
        byte[] key = { (byte)0x61, (byte)0xd0, (byte)0xad, (byte)0xde,
                       (byte)0x95, (byte)0xb0, (byte)0xf6, (byte)0x23 };
        BlowFish ec = new BlowFish(key);
        String s1 = "test";
        byte[] b1 = ec.encrypt(s1.getBytes());
        String s2 = new String(b64encode(b1));
        byte[] b2 = ec.decrypt(b1);
        String s3 = new String(b2);
        System.out.println(s1 + "->" + s2 + "->" + s3);
    }
}
