public static String base64Encode ( byte [ ] bytes ) { if ( bytes == null ) { throw new IllegalArgumentException ( "Input bytes must not be null." ) ; } if ( bytes . length >= BASE64_UPPER_BOUND ) { throw new IllegalArgumentException ( "Input bytes length must not exceed " + BASE64_UPPER_BOUND ) ; } // Every three bytes is encoded into four characters. // // Example: // input |0 1 0 1 0 0 1 0|0 1 1 0 1 1 1 1|0 1 1 0 0 0 1 0| // encode grouping |0 1 0 1 0 0|1 0 0 1 1 0|1 1 1 1 0 1|1 0 0 0 1 0| // encoded ascii | U | m | 9 | i | int triples = bytes . length / 3 ; // If the number of input bytes is not a multiple of three, padding characters will be added. if ( bytes . length % 3 != 0 ) { triples += 1 ; } // The encoded string will have four characters for every three bytes. char [ ] encoding = new char [ triples << 2 ] ; for ( int in = 0 , out = 0 ; in < bytes . length ; in += 3 , out += 4 ) { int triple = ( bytes [ in ] & 0xff ) << 16 ; if ( in + 1 < bytes . length ) { triple |= ( ( bytes [ in + 1 ] & 0xff ) << 8 ) ; } if ( in + 2 < bytes . length ) { triple |= ( bytes [ in + 2 ] & 0xff ) ; } encoding [ out ] = BASE64_CHARS . charAt ( ( triple >> 18 ) & 0x3f ) ; encoding [ out + 1 ] = BASE64_CHARS . charAt ( ( triple >> 12 ) & 0x3f ) ; encoding [ out + 2 ] = BASE64_CHARS . charAt ( ( triple >> 6 ) & 0x3f ) ; encoding [ out + 3 ] = BASE64_CHARS . charAt ( triple & 0x3f ) ; } // Add padding characters if needed. for ( int i = encoding . length - ( triples * 3 - bytes . length ) ; i < encoding . length ; i ++ ) { encoding [ i ] = ' ' ; } return String . valueOf ( encoding ) ; }
Base64 encodes a byte array .