A Developer's Diary

Dec 26, 2012

Advantages of Base64 Encoding

Base64 encoding is a technique used for converting binary data into blocks of printable ASCII characters. The Base64 encoding algorithm uses a special conversion table to assign one of the 64 ASCII characters to every 6 bits of the bytestream. That is to say, a binary stream is divided into blocks of six bits and each block is mapped to an ASCII character. The ASCII character with the value of 64 (character =) is used to signify the end of the binary stream.

Advantages
1. 7 Bit ASCII characters are safe for transmission over the network and between different systems
2. SMPT protocol for emails supports only 7 Bit ASCII Characters. Base64 is the commonly used technique to send binary files as attachments in emails.

Disadvantages
1. Base64 encoding bloats the size of the original binary stream by 33 percent
2. Encoding/Decoding process consumes resources and can cause performance problems

The program below makes use of the Apache Commons Codec library for Base64
encoding and decoding.
import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.codec.binary.Base64;

public class Base64EncodingDecodingDemo
{
    public static void main(String[] args)
    {
        File file = new File("C:/Thumbs.db");

        try
        {
            if (file.exists())
            {
                FileInputStream fis = new FileInputStream(file);

                // read the file contents in a byte array
                byte[] fileBytes = new byte[(int)file.length()];
                fis.read(fileBytes);

                // printing the binary stream as it is
                String data = new String(fileBytes);
                System.out.println(data);
                System.out.println("Original Stream Length: " + fileBytes.length);

                // getting base64 encoded string
                String encodeBase64String = Base64.encodeBase64String(fileBytes);
                System.out.println(encodeBase64String);
                System.out.println("Encoded Stream Length: " + encodeBase64String.getBytes().length);

                // decoding the base64 encoded string
                byte[] decodededString = Base64.decodeBase64(encodeBase64String);
                System.out.println("Decoded Stream Length: " + decodededString.length);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

References:
More on Base64 Encoding

2 comments :

Daniel said...

Thank you, this was very useful!

pankaj said...

Glad to know this. :)

Post a Comment