Data Encoding Tutorials - Herong's Tutorial Examples - v5.23, by Herong Yang
Java Built-In Implementation of Base64
This section provides a test program for the default Java implementation of the Base64 encoding algorithm java.util.Base64.Encoder.encode() and java.util.Base64.Decoder.decode() methods.
The Base64 encoding algorithm bas been implemented in Java language as 2 built-in methods since Java 8:
To test these built-in functions, I wrote this simple testing program:
/* Base64EncoderTest.java
* Copyright (c) 2002 HerongYang.com. All Rights Reserved.
*/
import java.io.*;
import java.util.Base64;
class Base64EncoderTest {
public static void main(String[] args) {
String theInput = null;
String theExpected = null;
System.out.println("Test 1:");
theInput = "A";
theExpected = "QQ==";
test(theInput, theExpected);
System.out.println("Test 2:");
theInput = "AB";
theExpected = "QUI=";
test(theInput, theExpected);
System.out.println("Test 3:");
theInput = "ABC";
theExpected = "QUJD";
test(theInput, theExpected);
System.out.println("Test 4:");
theInput = "The quick brown fox jumps over the lazy dog.";
theExpected =
"VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4=";
test(theInput, theExpected);
}
private static void test(String theInput, String theExpected) {
byte[] inputBytes = theInput.getBytes();
Base64.Encoder encoder = Base64.getEncoder();
byte[] encodedBytes = encoder.encode(inputBytes);
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(encodedBytes);
System.out.println(" Input : "+theInput);
System.out.println(" Encoded : "+new String(encodedBytes));
System.out.println(" Expected: "+theExpected);
System.out.println(" Decoded : "+new String(decodedBytes));
}
}
Here is the test result:
herong> java Base64EncoderTest.java Test 1: Input : A Encoded : QQ== Expected: QQ== Decoded : A Test 2: Input : AB Encoded : QUI= Expected: QUI= Decoded : AB Test 3: Input : ABC Encoded : QUJD Expected: QUJD Decoded : ABC Test 4: Input : The quick brown fox jumps over the lazy dog. Encoded : VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4= Expected: VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4= Decoded : The quick brown fox jumps over the lazy dog.
The result matches my expectation perfectly.
Table of Contents
►Base64 Encoding and Decoding Tools
Base64.Guru - Base64 Online Tool
Windows Command - "certutil -encode/-decode"
►Java Built-In Implementation of Base64
Java Built-In Implementation of MIME Base64
Python Built-In Implementation of Base64
Python Built-In Implementation of MIME Base64
PHP Built-In Implementation of Base64
PHP Built-In Implementation of MIME Base64
Perl Built-In Implementation of Base64
Perl Built-In Implementation of MIME Base64
Base64URL - URL Safe Base64 Encoding