1. Overview

In this example, We will learn Java Base64 encode decode example. Base64 is very popular for two way encoding and decoding of data. Here we have given an example of string to base64 and base64 to String using java. Sometimes developers used  sun.misc.BASE64Decoder and sun.misc.BASE64Encoder for decoding and encoding respectively but let me clarify that sun.misc consider as the internal package so we can not use its classes after Java 9 so Java is the generating warning like:

warning: sun.misc.BASE64Encoder is internal proprietary API and may be removed in a future release

Java also provides alternative to sun.misc.BASE64Decoder and sun.misc.BASE64Encoder here is example using java.util.Base64

2.String Base64 Encode/Decode

2.1.1. Encode String to Base64

package com.javadeveloperzone;

import java.util.Base64;

/**
 * Java Encode Text To Base64 Text Example
 * Created by JavaDeveloperZone on 20-02-2018.
 */
public class Base64Example {
    public static void main(String ... args){
        String text = "Java Developer Zone";
        String base64Text = Base64.getEncoder().encodeToString(text.getBytes());  // use decode() function if requires bytes instead of string
        System.out.println(base64Text);
    }
}

Output

SmF2YSBEZXZlbG9wZXIgWm9uZQ==

1.2 Encode Base64 to String

package com.javadeveloperzone;

import java.util.Base64;

/**
 * Encode Base64 to String
 * Created by JavaDeveloperZone on 20-02-2018.
 */
public class Base64Example {
    public static void main(String ... args){
        String base64 = "SmF2YSBEZXZlbG9wZXIgWm9uZQ==";   base64 string
        byte bytes[] = Base64.getDecoder().decode(base64);
        System.out.println("Plain Text : "+new String(bytes));   bytes to string
    }
}

Output:

Java Developer Zone

1.3 String Base64 Encoding without padding

If we are using without padding then decoding is not possible.

package com.javadeveloperzone;

import java.util.Base64;

/**
 * String Base64 Encode Without Padding
 * Created by JavaDeveloperZone on 20-02-2018.
 */
public class Base64Example {
    public static void main(String ... args){
        String base64 = "SmF2YSBEZXZlbG9wZXIgWm9uZQ==";
        byte bytes[] = Base64.getEncoder().withoutPadding().encode(base64.getBytes());  // without padding
        System.out.println("Base64 String : " + new String(bytes));
    }
}
Output:
Base64 String : U21GMllTQkVaWFpsYkc5d1pYSWdXbTl1WlE9PQ

 

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *