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:

HttpClient Timeout
Java Program to Implement Hash Tables with Quadratic Probing
Java Program to Implement Heap Sort Using Library Functions
Java Program to Describe the Representation of Graph using Incidence Matrix
Simple Single Sign-On with Spring Security OAuth2
Java Program to Represent Graph Using Adjacency List
Convert Hex to ASCII in Java
Java Program to Perform Sorting Using B-Tree
Creating a Web Application with Spring 5
How to Get All Dates Between Two Dates?
Spring Boot - Build Systems
Java Program to Check Whether Topological Sorting can be Performed in a Graph
Hướng dẫn sử dụng Lớp FilePermission trong java
String Joiner trong Java 8
Connect through a Proxy
Java Program to Implement Fenwick Tree
Cài đặt và sử dụng Swagger UI
Testing an OAuth Secured API with Spring MVC
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Java Program to Implement Sorted Circularly Singly Linked List
Java Program to find the maximum subarray sum using Binary Search approach
Java Program to Implement the String Search Algorithm for Short Text Sizes
Java Program to Implement Lloyd’s Algorithm
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Hướng dẫn Java Design Pattern – Abstract Factory
Ép kiểu trong Java (Type casting)
Practical Java Examples of the Big O Notation
Java Program to Find Number of Articulation points in a Graph
Default Password Encoder in Spring Security 5
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Ignore Null Fields with Jackson