I am wondering which library to use for base64 encoding/decoding? I need this functionality be stable enough for production use.
Basic Encoding and DecodingIt uses the Base64 alphabet specified by Java in RFC 4648 and RFC 2045 for encoding and decoding operations. The encoder does not add any line separator character. The decoder rejects data that contains characters outside the base64 alphabet.
What Does Base64 Mean? Base64 is an encoding and decoding technique used to convert binary data to an American Standard for Information Interchange (ASCII) text format, and vice versa.
Java 8 now has inbuilt encoder and decoder for Base64 encoding. In Java 8, we can use three types of Base64 encoding. Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.
The encodeToString() method will encode our input into a Base64 representation of the input, and pack it into a String. You can also use the encode() method to encode it into a byte stream or a ByteBuffer instead.
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 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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With