Simplest Way to Encode Base64 in Java
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 secureHTML5 App
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);