Base64 Encoding in Java

Since Java 8, Base64 encoding and decoding has become easier by using Base64 class from java itself.

How to implement in Java

package my.cychew;

import java.util.Base64;

public class Base64Encoding {

	public static void main(String[] args) {
		String stringToTest = "password";

		Base64Encoding t = new Base64Encoding();
		String encoded = t.encode(stringToTest);

		String decoded = t.decode(encoded);

		if (decoded.equals(stringToTest)) {
			System.out.println("==> match with stringToTest");
		} else {
			System.out.println("==> does not match");
		}
	}

	private String encode(String input) {
		System.out.println("Start encode [" + input + "]");
		byte[] encoded = Base64.getEncoder().encode(input.getBytes());
		System.out.println("encoded in byte[] = " + encoded);

		String result = new String(encoded);
		System.out.println("encoded in String = " + result);

		return result;
	}

	private String decode(String input) {
		System.out.println("Start decode [" + input + "]");
		byte[] decoded = Base64.getDecoder().decode(input.getBytes());
		System.out.println("decoded in byte[] = " + decoded);

		String result = new String(decoded);
		System.out.println("decoded in String = " + result);

		return result;
	}

}

Console Output

Start encode [password]
encoded in byte[] = [B@15db9742
encoded in String = cGFzc3dvcmQ=
Start decode [cGFzc3dvcmQ=]
decoded in byte[] = [B@6d06d69c
decoded in String = password
==> match with stringToTest
Base64 Encoding in Java
Tagged on:     

Leave a Reply

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