Encode/Decode to/from Base64

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.

1. Using java.util.Base64

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.

2. 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
       */
      }
}

3. 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>

4. 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();
    }
  }
}

5. Using MiGBase64

MiGBase64 is a very fast Base64 Codec written in Java. http://migbase64.sourceforge.net/.

Done! Happy Coding!

Related posts:

Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Converting Java Date to OffsetDateTime
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Apache Commons Collections SetUtils
Jackson Annotation Examples
Injecting Prototype Beans into a Singleton Instance in Spring
Custom Thread Pools In Java 8 Parallel Streams
Concrete Class in Java
Java Program to Find the Edge Connectivity of a Graph
Spring @RequestMapping New Shortcut Annotations
Java Program to Implement Fermat Primality Test Algorithm
Simple Single Sign-On with Spring Security OAuth2
Lớp Properties trong java
How to Remove the Last Character of a String?
Hướng dẫn Java Design Pattern – Chain of Responsibility
Introduction to Project Reactor Bus
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Quick Intro to Spring Cloud Configuration
JUnit5 Programmatic Extension Registration with @RegisterExtension
Java Program to Perform String Matching Using String Library
Java Program to Implement Interpolation Search Algorithm
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
Java CyclicBarrier vs CountDownLatch
Java Program to Check whether Graph is Biconnected
An Example of Load Balancing with Zuul and Eureka
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Debug a HttpURLConnection problem
Introduction to Spring Cloud Stream
Different Ways to Capture Java Heap Dumps
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
CharSequence vs. String in Java