HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 8 / Java Base64 Encoding and Decoding Examples

Java Base64 Encoding and Decoding Examples

In java 8 learning series, we already learned about new way to read a file line by line using streams. Java 8 introduced one more good addition related to IO operations and that is Base64 support. I this post, we will learn about it.

What is Base 64 encoding?

When you have some binary data that you want to ship across a network, you generally don’t do it by just converting data into stream of bits and bytes over the network in a raw format. Why? because some media are designed for streaming text only. These protocols may interpret your binary data as control characters which they are not.

Base 64 encoding convert your binary data into 64 printable ASCII characters. Generally it 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 encoded string with above characters is safe to be transferred over network supporting text data without fear of losing data in confusion of control characters.

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 an undocumented class sun.misc.BASE64Encoder. This class has also very limited information in public domain.

Base64 support from Java 8

Java 8 has added a class for Base 64 encoding and decoding purpose i.e. java.util.Base64. We will the code examples below for using it.

1) Encoding a string to base 64

This is as simple as getting an instance of 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) );

Output:

dXNlcm5hbWU6cGFzc3dvcmQ=

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));

Output:

username:password

3) Wrap to a base 64 encoded output stream

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 !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Vikrant

    February 5, 2015

    How to encode image to base64 in java 8?

  2. ravi

    May 5, 2014

    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

    • Lokesh Gupta

      May 6, 2014

      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.

      • ravi

        May 6, 2014

        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;
        }

Comments are closed on this article!

Search Tutorials

Java 8 Tutorial

  • Java 8 Features
  • Java 8 forEach
  • Java 8 Stream
  • Java 8 Boxed Stream
  • Java 8 Lambda Expression
  • Java 8 Functional Interface
  • Java 8 Method Reference
  • Java 8 Default Method
  • Java 8 Optional
  • Java 8 Predicate
  • Java 8 Regex as Predicate
  • Java 8 Date Time
  • Java 8 Iterate Directory
  • Java 8 Read File
  • Java 8 Write to File
  • Java 8 WatchService
  • Java 8 String to Date
  • Java 8 Difference Between Dates
  • Java 8 Join Array
  • Java 8 Join String
  • Java 8 Exact Arithmetic
  • Java 8 Comparator
  • Java 8 Base64
  • Java 8 SecureRandom
  • Internal vs External Iteration

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)