Java 8 – Base64 Encoding and Decoding

Java 8 introduced Base64 support to the IO operations. Let’s learn to encode and decode the inputs and outputs in Java 8.

1. What is Base 64 Encoding?

When we have some binary data that we want to send across a network, we generally don’t do it by just converting data into a stream of bits in a raw format.

Why? Because some media types are designed for streaming text only. These associated protocols may interpret our binary data as control characters which they are not.

Base-64 encoding converts our binary data into a string containing characters out of 64 printable characters. Generally, this encoding is done for binary data in email messages and "basic" HTTP authentication.

These 64 printable characters are:

  • 26 uppercase letters [A…Z]
  • 26 lowercase letters [a…z]
  • 10 digits [0…9]
  • 2 symbols [Read more]

The base-64 encoded string containing the above characters is safe to be transferred over the network supporting text data without fear of losing data in a confusion of control characters.

2. Base64 Support before Java 8

For many years, Java has provided support for base-64 via a non-public class (therefore non-usable) java.util.prefs.Base64 and an undocumented class sun.misc.BASE64Encoder. This class has also very limited information in the public domain.

3. Base64 Support since Java 8

Java 8 has added java.util.Base64 for Base-64 encoding and decoding purposes. It has two nested classes to work with the encoding and decoding process.

  • Base64.Encoder
  • Base64.Decoder

3.1. Encoding a String to Base-64

This is as simple as getting an instance of the Base64.Encoder and input the string as bytes to encode it.

Base64.Encoder encoder = Base64.getEncoder();
String normalString = "username:password";

String encodedString = encoder.encodeToString(
        normalString.getBytes(StandardCharsets.UTF_8) );
dXNlcm5hbWU6cGFzc3dvcmQ=

3.2. Decoding a Base-64 Encoded String

This is also very simple. Just get the instance of Base64.Decoder and use it to decode the base 64 encoded string.

String encodedString = "dXNlcm5hbWU6cGFzc3dvcmQ=";
Base64.Decoder decoder = Base64.getDecoder();

byte[] decodedByteArray = decoder.decode(encodedString);

//Verify the decoded string
System.out.println(new String(decodedByteArray));
username:password

3.3 Base-64 Encoded Streams

If you don’t want to directly work with data and rather prefer to work with streams, you can wrap the output stream such that all data written to this output stream will be automatically base 64 encoded.

Path originalPath = Paths.get("c:/temp", "mail.txt");
Path targetPath = Paths.get("c:/temp", "encoded.txt");

Base64.Encoder mimeEncoder = Base64.getMimeEncoder();

try(OutputStream output = Files.newOutputStream(targetPath))
{
    //Copy the encoded file content to target file
    Files.copy(originalPath, mimeEncoder.wrap(output));

    //Or simply use the encoded output stream
    OutputStream encodedStrem = mimeEncoder.wrap(output);
}

That’s all for this topic. This is already simple enough.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

4 thoughts on “Java 8 – Base64 Encoding and Decoding”

  1. warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

    How to solve this warning in java 6

    Reply
    • You get the error because sun.misc.BASE64Encoder is an internal API of the JDK. It’s not part of the official public Java API, so you are not supposed to be using it. There’s no guarantee that in a future Java update this class will still exist, and in other Java implementations (for example IBM’s JVM) this class doesn’t exist. Use this implementation.

      Reply
      • Hi Lokesh,

        I am attaching my method please check…

        public String getEncryotedCC(String plainText) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
        {
        DESKeySpec keySpec = new DESKeySpec(“Your secret Key phrase”.getBytes(“UTF8”));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(“DES”);
        SecretKey key = keyFactory.generateSecret(keySpec);
        BASE64Encoder base64encoder = new BASE64Encoder();

        byte[] cleartext = plainText.getBytes("UTF8");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        String encrypedString = base64encoder.encode(cipher.doFinal(cleartext));
        System.out.println("encrypedPwd : " + encrypedString);
        return encrypedString;
        }

        Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.