// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 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 B64old {
    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(), 0, baos.toByteArray().length - 1);
    }
    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);
        System.out.println(b[0] + " " + b[3]);
    }
}
