Base64 utils for Java

Last time I needed to add Base64 encoding to represent some binary data as a text. Especially I needed the functionality of translating a part (with given offset and length) of a byte array and get a result as a String object (listed in point “D” below). Surprisingly such an operation is not provided by most Base64 utils for Java. Below is the summary of my findings. I’ve focused on operations matching following signatures:

  1. byte[] encode(byte[] data)
  2. String encode(byte[] data)
  3. ByteBuffer encode(ByteBuffer data)
  4. String encode(byte[] data, int offset, int length)
  5. byte[] decode(byte[] base64)
  6. byte[] decode(String base64)
  7. ByteBuffer decode(ByteBuffer base64)
Name Remarks Operations
Java SE API Since Java 8, rather uncomfortable API (separate classes for coder and decoder) A, B, C, E, F, G
Apache Commons Codec It’s additional 293 KB. Many exotic operations. Maven dependency. A, B, E, F
Spring Framework Only an option if already using Spring, however it’s mostly an adapter using the one of the above libraries or JAXB DatatypeConverter as a fallback. Maven dependency. A, B, E, F
iHarder.net Base64 It weights only 17 KB! Many additional operations. Home page. Maven dependency. A, B, C, D, E, F
Guava Really heavy: 2.3 MB. Only an option if you’re already using Guava. Maven dependency. B, D, F

My personal favourite is iHarder.net Base64. Small and does the job. If performance is your strong requirement please refer to this article: Base64 encoding and decoding performance.

Advertisements

About krzysztoftomaszewski

I've got M.Sc. in software engineering. I graduated in 2005 at Institute of Computer Science, Warsaw University of Technology, Faculty of Electronics and Information Technology. I'm working on computer software design and engineering continuously since 2004.
This entry was posted in Java and tagged . Bookmark the permalink.

2 Responses to Base64 utils for Java

  1. Peter Lustig says:

    There is also:

    javax.xml.bind.DatatypeConverter.printBase64Binary(byte[])

    to encode a byte array with base64

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s