Share this page 

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 common ways to deal with Base64 encoding/decoding.

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

Using java.util.Base64
Available in Java 8 or better.

See http://docs.oracle.com/javase/8/docs/api/java/util/Base64.html

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Utils {

   private Base64Utils() {}

   public static String encode(String value) throws Exception {
      return  Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
   }

   public static String decode(String value) throws Exception {
      byte[] decodedValue = Base64.getDecoder().decode(value);  // Basic Base64 decoding
      return new String(decodedValue, StandardCharsets.UTF_8);
   }

   public static void main(String[] args) throws Exception {
      String test = "try this howto";

      String res1 = Base64Utils.encode(test);
      System.out.println
        (test + " base64 -> " + res1);

      //
      String res2 = Base64Utils.decode(res1);
      System.out.println( res1 + " string --> "  + res2);
      /*
       * output
       *   try this howto base64 -> dHJ5IHRoaXMgaG93dG8=
       *   dHJ5IHRoaXMgaG93dG8= string --> try this howto
       */
      }
}
java.util.Base64 supports three kinds of Base65 encoding/decoding (see the javadoc):

Regular Base64
Uses "The Base64 Alphabet" as specified in Table 1 of RFC 4648 and RFC 2045 for encoding and decoding operation. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
Mime Base64
Uses the "The Base64 Alphabet" as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return '\r' followed immediately by a linefeed '\n' as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.
URL Base64
Uses the "URL and Filename safe Base64 Alphabet" as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
Using javax.xml.bind.DatatypeConverter
This is one is using plain regular official Java 6+ API, no extra jar required.
import java.nio.charset.StandardCharsets; // java 7
import javax.xml.bind.DatatypeConverter;

public class Base64Utils {

   private Base64Utils() {}

   public static String encode(String value) throws Exception {
      return  DatatypeConverter.printBase64Binary
          (value.getBytes(StandardCharsets.UTF_8)); // use "utf-8" if java 6
   }

   public static String decode(String value) throws Exception {
      byte[] decodedValue = DatatypeConverter.parseBase64Binary(value);
      return new String(decodedValue, StandardCharsets.UTF_8); // use "utf-8" if java 6
   }

   public static void main(String[] args) throws Exception {
      String test = "try this howto";

      String res1 = Base64Utils.encode(test);
      System.out.println
        (test + " base64 -> " + res1);

      String res2 = Base64Utils.decode(res1);
      System.out.println( res1 + " string --> "  + res2);

      /*
       * output
       *  try this howto base64 -> dHJ5IHRoaXMgaG93dG8=
       *  dHJ5IHRoaXMgaG93dG8= string --> try t
       */
      }
}
Using javax.mail.internet.MimeUtility
This one is interesting because you can stream the data.
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
     */
    }

}
javax.mail.internet.MimeUtility is included in the JavaMail package.
<dependency>
   <groupId>javax.mail</groupId>
   <artifactId>mail</artifactId>
   <version>1.5.0-b01</version>
</dependency>
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/.