Base64 encoding is commonly used when there is a need to encode / decode binary data stored and transferred over network. It is used to encode and decode images, photos, audio etc as attachments in order to send through emails.
For Example Evolution and Thunderbird email clients use Base64 to obfuscate email passwords.
1. Using sun.misc.BASE64Encoder / sun.misc.BASE64Decoder Example
The best way to encode / decode in Base64 without using any third party libraries, you can use Using sun.misc.BASE64Encoder / sun.misc.BASE64Decoder. sun.* packages are not "officially supported" by Sun as it is proprietary classes, so there is chance to remove from jdk in future versions.
javax.mail.internet.MimeUtility is a part of JavaMail package and you can download the jar file from the following link JavaMail and should be in Class path
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); InputStream base64InputStream = MimeUtility.decode(bais, "base64"); byte[] tmp = new byte[baos.toByteArray().length]; int n = base64InputStream.read(tmp); byte[] res = new byte[n]; System.arraycopy(tmp, 0, res, 0, n); System.out.println("decoded String " + new String(res)); } }
Output
encoded String SmF2YVRpcHMubmV0
decoded String JavaTips.net
3. Using Apache Commons Codec Example
You can also use Apache Commons Codec for encode / decode in Base64. You can download the jar from the following link Apache Commons Codec and should be in Class path
import org.apache.commons.codec.binary.Base64;
// Apache Commons Codec Base64 Example
public class Base64Test {
public static void main(String[] args) {
byte[] encodedBytes = Base64.encodeBase64("JavaTips.net".getBytes()); System.out.println("encodedBytes " + new String(encodedBytes)); byte[] decodedBytes = Base64.decodeBase64(encodedBytes); System.out.println("decodedBytes " + new String(decodedBytes)); } }
Output
encodedBytes SmF2YVRpcHMubmV0
decodedBytes JavaTips.net
4. Using MiGBase64 Example
If
You are preferring performance based solution, then migbase64
outperform other libraries, You can download migbase64 jar from the
following link MiGBase64 and should be in ClassPath