Home » Core Java » apache » commons » codec » Encode Base64

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Encode Base64

In this example we shall show you how to encode Strings with the Base64 algorithm. We are using the org.apache.commons.codec.binary.Base64 class that provides Base64 encoding and decoding as defined by RFC 2045. To encode a String with Base64 one should perform the following steps:

  • Create a String.
  • Get the bytes from the String, using getBytes() API method of String.
  • Use encodeBase64(byte[] binaryData) method of org.apache.commons.codec.binary.Base64 to encode the byte array using the base64 algorithm.
  • Print the encoded array, using the toString(byte[] a) API method of Arrays,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import org.apache.commons.codec.binary.Base64;
import java.util.Arrays;
 
public class encodeBase64 {
	
    public static void main(String[] args) {

  
    	String string = "Javacodegeeks";
 

  // Get bytes from string

  byte[] byteArray = Base64.encodeBase64(string.getBytes());
 

  // Print the encoded byte array

  System.out.println(Arrays.toString(byteArray));
 

  // Print the encoded string

  String encodedString = new String(byteArray);

  System.out.println(string + " = " + encodedString);
    }
}

Output:

[83, 109, 70, 50, 89, 87, 78, 118, 90, 71, 86, 110, 90, 87, 86, 114, 99, 119, 61, 61]
Javacodegeeks = SmF2YWNvZGVnZWVrcw==

 
This was an example of how to encode a String with Base64 in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of