Home > Tutorial > Java Base64 Encode Decode Sample Code

Java Base64 Encode Decode Sample Code

With the roll out of Java 1.8 version, encoding and decoding strings in Base64 became a very simple task. The Base64 Encode class encodes byte data and the Base64 Decoder class decodes byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045. A NullPointerException will be thrown if a null argument is passed to any method of these classes.

Class Name Method Parameters Return Type Exceptions
Base64 getEncoder() none Base64.Encoder none
Base64 getDecoder() none Base64.Decoder none
Base64.Encoder encodeToString() byte [] String none
Base64.Decoder decode() String byte [] IllegalArgumentException

Java Base64 Encode Decode Source Code

package com.jcd.java.tutorials;

import java.util.Base64;

public class JavaBase64EncodeDecode 

	public static void main(String[] args) 
		//My original password (plain text)
		String myPassword = "Password";
		System.out.println("\nOriginal Password: "+myPassword);
		//My original password encoded using base64 to a series of characters/numbers/symbols
		String encodedPassword = Base64.getEncoder().encodeToString( myPassword.getBytes() );
		System.out.println("\nBase64 Encoded Password: "+encodedPassword);
		//Decode the encoded password into a byte array
		byte[] decodedByteArray = Base64.getDecoder().decode( encodedPassword );
		//Convert the decoded byte array back to a string (plain text)
		String decodedPassword = new String(decodedByteArray);
		System.out.println("\nBase64 Decoded Password: "+decodedPassword);



Java Base64 Encode Decode Output

Original Password: Password

Base64 Encoded Password: UGFzc3dvcmQ=

Base64 Decoded Password: Password

Java References:

Posted by


I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot