// 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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;

public class B64 {
    public static String b64encode(byte[] b) throws MessagingException, IOException  {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream b64os = MimeUtility.encode(baos, "base64");
        b64os.write(b);
        b64os.close();
        return new String(baos.toByteArray());
     }
     public static byte[] b64decode(String s) throws MessagingException, IOException  {
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());
        InputStream b64is = MimeUtility.decode(bais, "Base64");
        byte[] tmp = new byte[s.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[] b = { 1, 2, 3, 4 };
        String s = b64encode(b);
        System.out.println(s);
        byte[] b2 = b64decode(s);
        for(int i = 0; i < b2.length; i++) System.out.print(" " + b2[i]);
        System.out.println();
    }
}
