Real'sHowTo AddThis Feed Button
Custom Search

Encode/Decode to/from Base64Tag(s): String/Number Networking


As seen in this HowTo, the sun.misc.BASE64Encoder/Decoder or creating your own Base64 handling are the more common way to deal with Base64 encoding/decoding.

Here some alternatives which are maybe easier (and safer) to use.

Using javax.mail.internet.MimeUtility

import javax.mail.internet.MimeUtility;
import java.io.*;

public class Base64Utils {

  private Base64Utils() {}

  public static byte[] encode(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[] decode(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 {
    String test = "realhowto";
    byte res1[] = Base64Utils.encode(test.getBytes());
    System.out.println(test + " base64 -> " + java.util.Arrays.toString(res1));
    System.out.println(new String(res1));
    byte res2[] = Base64Utils.decode(res1);
    System.out.println("");
    System.out.println( java.util.Arrays.toString(res1) + " string --> "
        + new String(res2));
    /*
     * output
     * realhowto base64 ->
     *     [99, 109, 86, 104, 98, 71, 104, 118, 100, 51, 82, 118]
     *     cmVhbGhvd3Rv
     * [99, 109, 86, 104, 98, 71, 104, 118, 100, 51, 82, 118]
     *     string --> realhowto
     */
    }

}

Using Apache Commons Codec

Apache Commons Codec provides implementations of common encoders and decoders such as Base64, Hex, Phonetic and URLs.

Download at http://commons.apache.org/codec/

import org.apache.commons.codec.binary.Base64;

public class Codec {
  public static void main(String[] args) {
    try {
      String clearText = "Hello world";
      String encodedText;

      // Base64
      encodedText = new String(Base64.encodeBase64(clearText.getBytes()));
      System.out.println("Encoded: " + encodedText);
      System.out.println("Decoded:"
          + new String(Base64.decodeBase64(encodedText.getBytes())));
      //
      // output :
      //   Encoded: SGVsbG8gd29ybGQ=
      //   Decoded:Hello world
      //
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

MiGBase64

  • MiGBase64 is a very fast Base64 Codec written in Java. http://migbase64.sourceforge.net/.
    blog comments powered by Disqus


    If you find this article useful, consider making a small donation
    to show your support for this Web site and its content.

    Written and compiled by Réal Gagnon ©1998-2014
    [ home ]