Encoding and Decoding of String in Java using base64 are extremely easy if you are using Apache commons code open source library. it provides convenient static utility methods Base64.encodeBase64(byte[]) and Base64.decodeBase64(byte []) for converting binary data into base64 encoded binary Stream and then decoding back from encoded data in base64 encoding mechanism. Many times we need to encode sensitive data be it binary String format transferring over a socket or transferring or storing data in XML files. Though there are other open-source libraries available that provide support to encode any String into base64 like MimeUtil from javax.mail package but Apache commons-codec package is really handy and doesn't add a lot of extra stuff. Its API is also very neat and clean. In this article, we will see how to encode and decode String into base64 encoding.
Base64 Encoding Algorithm
For those who are not familiar with the base64 encoding algorithm here is the basic introduction. Base64 encodes (changes content of original String) String using an algorithm that uses 64 printable characters to replace each character in an original string in an algorithmic sequence so that it can be decoded later. Base64 encoding prevents misuse of data by encoding it into ASCII format.
Though there are more advanced encryption algorithms available like RSA-SHA and MD5 and you should use those in production but base64 is real simple and easy to use for simple encoding needs.
Though there are more advanced encryption algorithms available like RSA-SHA and MD5 and you should use those in production but base64 is real simple and easy to use for simple encoding needs.
Encoding and Decoding String into Base64 Java
Here is a quick example of the encoding and decoding of String in the base64 encoding algorithm. we will first encode String by converting it into a byte array and then passing it down to Base64.encodeBase64(byte[]) which encodes byte array as per the base64 encoding algorithm and returns an encoded byte array, which can be converted into String.
Later half, we will decode the String by calling Base64.decodeBase64(byte[]) method. By the way, if you like to learn more about String, there are a lot of articles related to String in java e.g. Why to char array is preferred over String for storing the password and Why String is immutable in Java, which you may like.
import org.apache.commons.codec.binary.Base64;
/**
* Java program to encode and decode String in Java using the Base64 encoding algorithm
* @author http://javarevisited.blogspot.com
*/
public class Base64EncodingExample{
public static void main(String args[]) throws IOException {
String orig = "original String before base64 encoding in Java";
//encoding byte array into base 64
byte[] encoded = Base64.encodeBase64(orig.getBytes());
System.out.println("Original String: " + orig );
System.out.println("Base64 Encoded String : " + new String(encoded));
//decoding byte array into base64
byte[] decoded = Base64.decodeBase64(encoded);
System.out.println("Base 64 Decoded String : " + new String(decoded));
}
}
Output:
Original String: original String before base64 encoding in Java
Base64 Encoded String : b3JpZ2luYWwgU3RyaW5nIGJlZm9yZSBiYXNlNjQgZW5jb2RpbmcgaW4gSmF2YQ==
Base 64 Decoded String : original String before base64 encoding in Java
Dependency
In order to execute this Base64 Encoding Example in Java, you need to download and add commons-codec-1.2.jar into your application classpath. if you are using Maven for managing your project dependency you can include the following
dependency in pom.xml:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>20041127.091804</version>
</dependency>
This is a very simple and clean base64 encoding example in Java but serves the purpose. That's all in how to encode Java String into Base64 encoding and how to decode Java String. let me know if you face any issues.
Other Java Tutorials you may like:
We can also use:
ReplyDeletenew sun.misc.BASE64Encoder().encode()
new sun.misc.BASE64Decoder().decode()
It comes with the JDK, no need for extra dependencies.
base64 is NOT encryption! It is encoding.
ReplyDelete@Anonymous, new sun.misc.BASE64Encoder() seems a good option, does it available in all JDK or its added from Java 5 or 6? I agree this should be first preferred choice if available because it removes extra dependency. Thanks
ReplyDelete@Anonymous, Indeed base64 is not encryption because it doesn't involve any private or public key combination. I have used loose terminology where encoding is encryption servers similar purpose of changing data from clear text. but yes in precise terms its not encryption. thanks
ReplyDelete@Anonymous, There is also a risk of using new sun.misc.BASE64Encoder() because its part of non public API as sun may change it or it may not work on other JVM like Webshpere server which uses IBM's JVM. I come to know about this when I tried to use it and I got error on Eclipse "Access restriction: The type BASE64Decoder is not accessible due to restriction on required library"
ReplyDeletejavax.xml.bind.DatatypeConverter contains two static methods parseBase64Binary and printBase64Binary. The class is part of the JRE since Java 1.6.
ReplyDeleteNo need for roll-your-own or undocumented classes anymore.
http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html
You are mixing encryption and encoding in the introduction: an encryption provides confidentiality whereas encoding simply provides robustness w/ or w/o advances concerning size and error correction.
ReplyDelete@Anonymous, Thanks for pointing it out DatatypeConverter, I am gonna look that but if it can work like Base64Encoder.encode() or able to covert byte array into base64 encoding that no doubt its an excellent choice, only thing is it looks like available from JDK6 onwards so if your project is in Java 5 and you are not upgrading it to Java 6 than Apache commons codec is still a good choice.
ReplyDelete@Anonymous, Indeed there is difference in encoding and encryption and encryption is more robust and secure. Thanks for your comment.
ReplyDeleteThanks for the good article
ReplyDeleteyou can also check following article
Encode And Decode In Base64 Using Java
@Anonymous: thank you, javax.xml.bind.DatatypeConverter seems to work okay for me!
ReplyDelete(The sun.misc.BASE64Encoder is not recommended, netbeans warns about it as well.)
also, i would add that if you want this to work with all kinds of characters (accented, etc.), replace getBytes() with getBytes("UTF8") and new String(something) with new String(something, "UTF8")
ReplyDeleteJava 8 is adding new standard API for Base64 encoding and decoding, which means no need to use Apache commons code or sun.misc.BASE64Encoder and sun.misc.BASE64Decoder. Wait for Java 1.8, you will have more cleaner way to encode String in Base64.
ReplyDeletedoes this encoding system use of & character ???
ReplyDeletei would like to use it on my link URL ???
Thank you, this tutorial help me to encode byte array in RC4 encryption
ReplyDeletehttp://sleepingtux.blogspot.com
Hi
ReplyDeleteJava 8 introduces a formal API for base64 encoding - no more sun/oracle propriety or additional libraries are needed. You can see more at: http://blog.eyallupu.com/2013/11/base64-encoding-in-java-8.html
The Base64.Encoder and Base64.Decoder classes from JDK 8 is much faster than both Apache commons Encoder and Sun's old base 64 encoder class. If you are running on Java 8, there is no reason to any other library for base 64 encoidng.
ReplyDeleteThe Base64.Encoder and Base64.Decoder classes from JDK 8 is much faster than both Apache commons Encoder and Sun's old base 64 encoder class. If you are running on Java 8, there is no reason to any other library for base 64 encoidng.
ReplyDelete