Which Java library provides base64 encoding/decoding?

Java

Java Problem Overview


I am wondering which library to use for base64 encoding/decoding? I need this functionality be stable enough for production use.

Java Solutions


Solution 1 - Java

Java 9

Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind module which will need to be included.

module org.example.foo {
    requires java.xml.bind;
}

Java 8

Java 8 now provides java.util.Base64 for encoding and decoding base64.

Encoding

byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=

Decoding

byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world

Java 6 and 7

Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter can be used. This is part of the JRE, no extra libraries required.

Encoding

byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=  

Decoding

byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world

Solution 2 - Java

Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.

Via Maven:

<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>20041127.091804</version>
</dependency>

Direct Download

Solution 3 - Java

If you're an Android developer you can use android.util.Base64 class for this purpose.

Solution 4 - Java

Guava also has Base64 (among other encodings and incredibly useful stuff)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam LeeView Question on Stackoverflow
Solution 1 - JavaAdamView Answer on Stackoverflow
Solution 2 - JavaKevin BowersoxView Answer on Stackoverflow
Solution 3 - JavaPawanView Answer on Stackoverflow
Solution 4 - JavaJB NizetView Answer on Stackoverflow