Interview Questions

Java Base64 Encoding

Base64Encoding.java

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.IOException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * The following program is used to perform simple Base64 Encoding in Java.
 */

public class Base64Encoding
{
        public static void main(String[] args)
        {
                Base64Encoding b64 = new Base64Encoding();

                String originalString = "techdive";
                String encodedString = b64.encodeStringBase64(originalString);
                String decodedString = b64.decodeStringBase64(encodedString);

                System.out.println("Original String Value - > " + originalString);
                System.out.println("Encoded String Value - > " + encodedString);
                System.out.println("Decoded String Value - > " + decodedString);
        }

        public String encodeStringBase64(String s)
        {
                BASE64Encoder encoder = new BASE64Encoder();
                return encoder.encodeBuffer(s.getBytes()).trim();
        }

        public String decodeStringBase64(String s)
        {
                BASE64Decoder dec = new BASE64Decoder();
                String decodedStr = "";
                try
                {
                        decodedStr = new String(dec.decodeBuffer(s));
                }
                catch (IOException e)
                {
                        System.out.println("Exception Occured -> " + e.getMessage());
                }
                return decodedStr;
        }
}

Output:

Original String Value - > techdive
Encoded String Value - > dGVjaGRpdmU=
Decoded String Value - > techdive