codec

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button