December 7th, 2017

Base64 encoding and decoding in Java 8

APIs, Core Java, Development Tools, Java Language, Learn Java, others, Programing, by admin.

Java 8 will be remembered mainly for introducing lambdas, streams, a new date/time model, and the Nashorn JavaScript engine to Java. Some will also remember Java 8 for introducing various small but useful features such as the Base64 API. What is Base64 and how do I use this API? This post answers these questions.

What is Base64?

Base64 is a binary-to-text encoding scheme that represents binary data in a printable ASCII string format by translating it into a radix-64 representation. Each Base64 digit represents exactly 6 bits of binary data.

Base64 is used to prevent data from being modified while in transit through information systems, such as email, that might not be 8-bit clean (they might garble 8-bit values). For example, you attach an image to an email message and want the image to arrive at the other end without being garbled. Your email software Base64-encodes the image and inserts the equivalent text into the message, as illustrated below:

Content-Disposition: inline; filename=IMG_0006.JPG
Content-Transfer-Encoding: base64 /9j/4R/+RXhpZgAATU0AKgAAAAgACgEPAAIAAAAGAAAAhgEQAAIAAAAKAAAAjAESAAMAAAABAAYA
AAEaAAUAAAABAAAAlgEbAAUAAAABAAAAngEoAAMAAAABAAIAAAExAAIAAAAHAAAApgEyAAIAAAAU
AAAArgITAAMAAAABAAEAAIdpAAQAAAABAAAAwgAABCRBcHBsZQBpUGhvbmUgNnMAAAAASAAAAAEA
...
NOMbnDUk2bGh26x2yiJcsoBIrvtPe3muBbTRGMdeufmH+Nct4chUXpwSPk/qK9GtJRMWWVFbZ0JH
I4rf2dkZSbOjt7hhEzwcujA4I7Gust75pYVwAPpXn+kzNLOVYD7xFegWEKPkHsM/pU1F0NKbNS32
o24sSCOlaaFYLUhjky4x9PSsKL5bJsdWkAz3xirH2dZLy1DM2C44zx1FZqL2PTXY/9k=

The illustration shows that this encoded image starts with / and ends with =. The ... indicates text that I haven’t shown for brevity. Note that the entire encoding for this or any other example is about 33 percent larger than the original binary data.

Back Top

Leave a Reply