Base64 Encoding/Decoding with javax.xml.bind.DatatypeConverter in java 6 and 7.
Solution: javax.xml.bind.Datatypeconverter class is the built in class inside JRE. We don’t need any third party library as we need in case of Cipher encoding/decoding method. javax.xml.bind.DatatypeConverter.printBase64Binary(byte[]) encodes a byte[] array into a Base64 encoded string.
1. Encode text with base64 using javax.xml.bind.Datatypeconverter:
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class EncodeText {
public static void main(String[] args) {
String textToEncode = "Encoding with DatatypeConverter";
byte[] message = null;
try {
message = textToEncode.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String encodedText = DatatypeConverter.printBase64Binary(message);
System.out.println(encodedText);
}
}
Output: RW5jb2Rpbmcgd2l0aCBEYXRhdHlwZUNvbnZlcnRlcg==
2. Decode text with base64 using javax.xml.bind.Datatypeconverter:
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class DecodeText {
public static void main(String[] args) {
String encodedString = “RW5jb2Rpbmcgd2l0aCBEYXRhdHlwZUNvbnZlcnRlcg == ";
String decodedText = null;
byte[] decodedTextBytes = null;
decodedTextBytes = DatatypeConverter.parseBase64Binary(encodedString);
try {
decodedText = new String(decodedTextBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(decodedText);
}
}
Output: Encoding with DatatypeConverter
