Introduction


The example Java program below shows how to encode and decode a string using the Base64 algorithm. Base64 encoding is used to convert binary data into a text-like format to be transported in environments that handle only text safely. For example, encoding UID's for use in HTTP URL's or to encode encryption keys to make them safely portable through e-mail, display them in HTML pages and use them with copy and paste.

The example below is a raw implementation to illustrate the algorithm. For programming convenience, several Java classes implement functions for base64 handling.

/* --------------------------------------------------------------------- *
 * file:        base64_stringencode.java v1.0                            *
 * purpose:     tests encoding/decoding strings with base64              *
 * author:      07/25/2012 Frank4DD                                      *
 *                                                                       *
 * This program encodes and decodes a sample string with base64 format.  *
 * --------------------------------------------------------------------- */

public class base64_stringencode {

  /* ---- Base64 Encoding/Decoding Table --- */
  private static final char b64[] = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
      'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
      'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
      'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
      'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
      'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
      'w', 'x', 'y', 'z', '0', '1', '2', '3',
      '4', '5', '6', '7', '8', '9', '+', '/'
  };

  private static String encode(String string) {
    String b64String = "";
    byte     bytes[] = string.getBytes();
    int          pad = 0;
    int            i = 0;

    while (i < bytes.length) {
      byte b1 = bytes[i++];
      byte b2;
      byte b3;

      if (i >= bytes.length) {
         b2 = 0;
         b3 = 0;
         pad = 2;
      }
      else {
         b2 = bytes[i++];
         if (i >= bytes.length) {
            b3 = 0;
            pad = 1;
         }
         else b3 = bytes[i++];
      }
      byte c1 = (byte)(b1 >> 2);
      byte c2 = (byte)(((b1 & 0x3) << 4) | (b2 >> 4));
      byte c3 = (byte)(((b2 & 0xf) << 2) | (b3 >> 6));
      byte c4 = (byte)(b3 & 0x3f);
      b64String += b64[c1];
      b64String += b64[c2];
      switch (pad) {
       case 0:
         b64String += b64[c3];
         b64String += b64[c4];
         break;
       case 1:
         b64String += b64[c3];
         b64String += "=";
         break;
       case 2:
         b64String += "==";
         break;
      }
    }
    return b64String;
  }

  private static int[]  toInt = new int[128];

  static {
    for(int i=0; i < b64.length; i++){
      toInt[b64[i]]= i;
    }
  }

  private static String decode(String s){
    int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0;
    int len = s.length()*3/4 - delta;
    byte[] buffer = new byte[len];
    String clrstr = "";
    int mask = 0xFF;
    int index = 0;

    for(int i=0; i< s.length(); i+=4){
      int c0 = toInt[s.charAt(i)];
      int c1 = toInt[s.charAt(i + 1)];
      buffer[index++]= (byte)(((c0 << 2) | (c1 >> 4)) & mask);
      if(index >= buffer.length){
        clrstr = new String(buffer);
        return clrstr;
      }
      int c2 = toInt[s.charAt(i + 2)];
      buffer[index++]= (byte)(((c1 << 4) | (c2 >> 2)) & mask);
      if(index >= buffer.length){
        clrstr = new String(buffer);
        return clrstr;
      }
      int c3 = toInt[s.charAt(i + 3)];
      buffer[index++]= (byte)(((c2 << 6) | c3) & mask);
    }
    clrstr = new String(buffer);
    return clrstr;
  } 

  public static void main (String args[]) {

    String mysrc = "My bonnie is over the          ";
    String myb64 = "";
    String mydst = "";

    myb64 = encode(mysrc);
    System.out.println("The string\n["+mysrc+"]\nencodes into base64 as:\n["+myb64+"]\n");

    mydst = decode(myb64);
    System.out.println("The string\n["+myb64+"]\ndecodes from base64 as:\n["+mydst+"]\n");
  }
}

After compiling the Java program with javac base64_stringencode.java, running it returns the following output:

fm@susie114:~> java base64_stringencode
The string
[My bonnie is over the          ]
encodes into base64 as:
[TXkgYm9ubmllIGlzIG92ZXIgdGhlICAgICAgICAgIA==]

The string
[TXkgYm9ubmllIGlzIG92ZXIgdGhlICAgICAgICAgIA==]
decodes from base64 as:
[My bonnie is over the          ]

Remarks


From the mentioned list of Java libraries for Base64 I want to recommend the following, located at http://iharder.net/base64. Simply Download the Base64.java file, compile it together with your code, and voila, the externally provided Base64 functions will shorten your code substantially. The example code below generates the exact same output as the former code listed above.

/* --------------------------------------------------------------------- *
 * file:        base64_stringencode2.java v1.0                           *
 * purpose:     tests encoding/decoding strings with base64              *
 * author:      07/25/2012 Frank4DD                                      *
 *                                                                       *
 * This program encodes and decodes a sample string with base64 format,  *
 * using the Base64 functions provided at http://iharder.net/base64.     *
 *                                                                       *
 * compile:     javac Base64.java base64_stringencode2.java              *
 * --------------------------------------------------------------------- */

class base64_stringencode2 {
  public static void main (String args[]) {

    String mysrc = "My bonnie is over the          ";
    String myb64 = "";
    String mydst = "";

    try {
      myb64 = Base64.encodeBytes(mysrc.getBytes());
      System.out.println("The string\n["+mysrc+"]\nencodes into base64 as:\n["+myb64+"]\n");

      mydst = new String (Base64.decode(myb64));
      System.out.println("The string\n["+myb64+"]\ndecodes from base64 as:\n["+mydst+"]\n");
    }
    catch (java.io.IOException e)
     { System.err.println("IO Error, the Base64 functions data input failed."); }
  }
}

Another advantage of this library is the ability to automatically handle newlines in base64 encoding and decoding, as well as data compression, simply by providing the appropriate options to the function calls.

Sample Code:

See Also: