Decode Base64 data in Java

As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter has static methods that make this easy. See parseBase64Binary() and printBase64Binary().


As of Java 8, there is an officially supported API for Base64 encoding and decoding. In time this will probably become the default choice.

The API includes the class java.util.Base64 and its nested classes. It supports three different flavors: basic, URL safe, and MIME.

Sample code using the "basic" encoding:

import java.util.Base64;

byte[] bytes = "Hello, World!".getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);

The documentation for java.util.Base64 includes several more methods for configuring encoders and decoders, and for using different classes as inputs and outputs (byte arrays, strings, ByteBuffers, java.io streams).


No need to use commons--Sun ships a base64 encoder with Java. You can import it as such:

import sun.misc.BASE64Decoder;

And then use it like this:

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);

Where encodedBytes is either a java.lang.String or a java.io.InputStream. Just beware that the sun.* classes are not "officially supported" by Sun.

EDIT: Who knew this would be the most controversial answer I'd ever post? I do know that sun.* packages are not supported or guaranteed to continue existing, and I do know about Commons and use it all the time. However, the poster asked for a class that that was "included with Sun Java 6," and that's what I was trying to answer. I agree that Commons is the best way to go in general.

EDIT 2: As amir75 points out below, Java 6+ ships with JAXB, which contains supported code to encode/decode Base64. Please see Jeremy Ross' answer below.

Tags:

Java

Base64