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

import javax.mail.internet.MimeUtility;

public class B64Encode 
{
   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[] b = new byte[512];
      for(int i = 0; i < b.length; i++) b[i] = (byte)(i % 256);
      byte[] b2 = b64encode(b);
      //System.out.println(new String(b2));
      byte[] b3 = b64decode(b2);
      for(int i = 0; i < b.length; i++) {
         if(b[i] != b3[i]) {
            System.out.println(i + " " + b[i] + " " + b3[i]);
         }
      }
   }
}
