public static String encode(byte[] data){
  int start=0;
  int len=data.length;
  StringBuffer buf=new StringBuffer(data.length * 3 / 2);
  int end=len - 3;
  int i=start;
  int n=0;
  while (i <= end) {
    int d=((((int)data[i]) & 0x0ff) << 16) | ((((int)data[i + 1]) & 0x0ff) << 8) | (((int)data[i + 2]) & 0x0ff);
    buf.append(legalChars[(d >> 18) & 63]);
    buf.append(legalChars[(d >> 12) & 63]);
    buf.append(legalChars[(d >> 6) & 63]);
    buf.append(legalChars[d & 63]);
    i+=3;
    if (n++ >= 14) {
      n=0;
    }
  }
  if (i == start + len - 2) {
    int d=((((int)data[i]) & 0x0ff) << 16) | ((((int)data[i + 1]) & 255) << 8);
    buf.append(legalChars[(d >> 18) & 63]);
    buf.append(legalChars[(d >> 12) & 63]);
    buf.append(legalChars[(d >> 6) & 63]);
    buf.append("=");
  }
 else   if (i == start + len - 1) {
    int d=(((int)data[i]) & 0x0ff) << 16;
    buf.append(legalChars[(d >> 18) & 63]);
    buf.append(legalChars[(d >> 12) & 63]);
    buf.append("==");
  }
  return buf.toString();
}

public static String encode ( byte [ ] data ) { int start = 0 ; int len = data . length ; StringBuffer buf = new StringBuffer ( data . length * 3 / 2 ) ; int end = len - 3 ; int i = start ; int n = 0 ; while ( i <= end ) { int d = ( ( ( ( int ) data [ i ] ) & 0x0ff ) << 16 ) | ( ( ( ( int ) data [ i + 1 ] ) & 0x0ff ) << 8 ) | ( ( ( int ) data [ i + 2 ] ) & 0x0ff ) ; buf . append ( legalChars [ ( d > > 18 ) & 63 ] ) ; buf . append ( legalChars [ ( d > > 12 ) & 63 ] ) ; buf . append ( legalChars [ ( d > > 6 ) & 63 ] ) ; buf . append ( legalChars [ d & 63 ] ) ; i += 3 ; if ( n ++ >= 14 ) { n = 0 ; } } if ( i == start + len - 2 ) { int d = ( ( ( ( int ) data [ i ] ) & 0x0ff ) << 16 ) | ( ( ( ( int ) data [ i + 1 ] ) & 255 ) << 8 ) ; buf . append ( legalChars [ ( d > > 18 ) & 63 ] ) ; buf . append ( legalChars [ ( d > > 12 ) & 63 ] ) ; buf . append ( legalChars [ ( d > > 6 ) & 63 ] ) ; buf . append ( "=" ) ; } else if ( i == start + len - 1 ) { int d = ( ( ( int ) data [ i ] ) & 0x0ff ) << 16 ; buf . append ( legalChars [ ( d > > 18 ) & 63 ] ) ; buf . append ( legalChars [ ( d > > 12 ) & 63 ] ) ; buf . append ( "==" ) ; } return buf . toString ( ) ; }
base64 encode the given data .
