Home > Software Development > Simplest Way to Encode Base64 in Java

Simplest Way to Encode Base64 in Java

February 3rd, 2014 Leave a comment Go to comments

Base64 is a straight forward encoding for binary data into readable characters (RFC 4648 and RFC 2045). Although you can do it by yourself, more often than not you would like use an existing library, for example, Apache common. If you just need the Base64 encoding but have to import the whole library, it’s not a good idea. There is actually a better way without introducing extra dependency, which is to hack Java standard library 1.6.

The Java class is the javax.xml.bind.DatatypeConverter, which is part of the XML package (JAXB) and has a method called printBase64Binary() that takes in a byte array and returns a encoded BASE64 string. The reason for it to be there is that XML requires Base64 encoding support. What’s coming next is not an intended usage, but it works just fine. That is why I called this a hack. In Java 1.8, a new class has been added into the java.util package. You should use that class if you use Java 1.8 in the future.

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure


The following is a code snippet that encoding the user name and password for BASIC Authentication for Web applications. It combines a user name and corresponding password with “:” as delimiter, and converts it to an byte array that can be feed into the printBase64Binary(). Once the encoded string is ready, just set it as value to the Authorization header.

The following code is how to do the encoding and set it as a HTTP header in request to server:

import javax.xml.bind.DatatypeConverter;
      String encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
      urlConn.setRequestProperty("Authorization", "Basic " + encoding);

Depending the client library, your API to set the header could be different. For example, if you use Apache Thrift’s HTTP transport, the code may look like the following:

import org.apache.thrift.transport.THttpClient;
transport.setCustomHeader("Authorization", "Basic " + encoding);
  1. March 3rd, 2015 at 15:23 | #1

    great article, very usefull,
    I use this site to encode/decode base 64.

  2. May 1st, 2015 at 11:48 | #2

    Thanks. This was more straightforward help than what I found on StackOverflow.

  3. Jeff Power
    January 21st, 2016 at 20:57 | #3

    thanks for sharing .. is this “printBase64Binary() that takes in a byte array and returns a encoded BASE64 string” considered to be used for AES 256 based encryption?.

  4. January 22nd, 2016 at 14:15 | #4

    You are welcome Jeff, the base64 is not encryption but a type of encoding.


  1. No trackbacks yet.