public static byte [ ] decode ( final String data ) { if ( data == null ) { throw new IllegalArgumentException ( SR . STRING_NOT_VALID ) ; } int byteArrayLength = 3 * data . length ( ) / 4 ; if ( data . endsWith ( "==" ) ) { byteArrayLength -= 2 ; } else if ( data . endsWith ( "=" ) ) { byteArrayLength -= 1 ; } final byte [ ] retArray = new byte [ byteArrayLength ] ; int byteDex = 0 ; int charDex = 0 ; for ( ; charDex < data . length ( ) ; charDex += 4 ) { // get 4 chars, convert to 3 bytes final int char1 = DECODE_64 [ ( byte ) data . charAt ( charDex ) ] ; final int char2 = DECODE_64 [ ( byte ) data . charAt ( charDex + 1 ) ] ; final int char3 = DECODE_64 [ ( byte ) data . charAt ( charDex + 2 ) ] ; final int char4 = DECODE_64 [ ( byte ) data . charAt ( charDex + 3 ) ] ; if ( char1 < 0 || char2 < 0 || char3 == - 1 || char4 == - 1 ) { // invalid character(-1), or bad padding (-2) throw new IllegalArgumentException ( SR . STRING_NOT_VALID ) ; } int tVal = char1 << 18 ; tVal += char2 << 12 ; tVal += ( char3 & 0xff ) << 6 ; tVal += char4 & 0xff ; if ( char3 == - 2 ) { // two "==" pad chars, check bits 12-24 tVal &= 0x00FFF000 ; retArray [ byteDex ++ ] = ( byte ) ( tVal >> 16 & 0xFF ) ; } else if ( char4 == - 2 ) { // one pad char "=" , check bits 6-24. tVal &= 0x00FFFFC0 ; retArray [ byteDex ++ ] = ( byte ) ( tVal >> 16 & 0xFF ) ; retArray [ byteDex ++ ] = ( byte ) ( tVal >> 8 & 0xFF ) ; } else { // No pads take all 3 bytes, bits 0-24 retArray [ byteDex ++ ] = ( byte ) ( tVal >> 16 & 0xFF ) ; retArray [ byteDex ++ ] = ( byte ) ( tVal >> 8 & 0xFF ) ; retArray [ byteDex ++ ] = ( byte ) ( tVal & 0xFF ) ; } } return retArray ; }
Decodes a given Base64 string into its corresponding byte array .