1 38 package com.gargoylesoftware.htmlunit; 39 40 import java.io.UnsupportedEncodingException ; 41 42 49 public final class Base64 { 50 51 private static final byte[] ENCODING_TABLE; 52 53 private static final byte PADDING_BYTE; 54 55 static { 56 final String table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 57 try { 58 ENCODING_TABLE = table.getBytes( "ISO-8859-1" ); 59 PADDING_BYTE = "=".getBytes( "ISO-8859-1" )[0]; 60 } 61 catch( final UnsupportedEncodingException e ) { 62 throw new IllegalStateException ( 63 "Theoretically impossible: ISO-8859-1 (us-ascii) is not a supported encoding" ); 64 } 65 66 if( ENCODING_TABLE.length != 64 ) { 67 throw new IllegalStateException ( "Encoding table doesn't contain 64 values" ); 68 } 69 } 70 71 72 private Base64() { 73 } 74 75 76 82 public static String encode( final String input ) { 83 try { 84 return encode( input, "ISO-8859-1" ); 85 } 86 catch( final UnsupportedEncodingException e ) { 87 throw new IllegalStateException ( 88 "Theoretically impossible: ISO-8859-1 (us-ascii) is not a supported encoding" ); 89 } 90 } 91 92 93 101 public static String encode( final String input, final String characterEncoding ) 102 throws UnsupportedEncodingException { 103 104 return new String ( encode( input.getBytes( characterEncoding ) ), characterEncoding ); 105 } 106 107 108 114 public static byte[] encode( final byte[] array ) { 115 final int paddingCharCount = ( 3 - ( array.length % 3 ) ) % 3; 116 117 final byte[] input; 118 119 if( paddingCharCount == 0 ) { 120 input = array; 121 } 122 else { 123 input = new byte[array.length + paddingCharCount]; 124 System.arraycopy( array, 0, input, 0, array.length ); 125 } 126 127 final byte output[] = new byte[( input.length * 4 / 3 )]; 128 int outputIndex = 0; 129 130 byte byte1; 131 byte byte2; 132 byte byte3; 133 134 for( int i = 0; i < input.length; i += 3 ) { 135 byte1 = input[i]; 136 byte2 = input[i + 1]; 137 byte3 = input[i + 2]; 138 139 output[outputIndex++] = ENCODING_TABLE[( byte1 & 0xFC ) >>> 2]; 140 output[outputIndex++] = ENCODING_TABLE[( ( byte1 & 0x03 ) << 4 ) 141 | ( ( byte2 & 0xF0 ) >>> 4 )]; 142 output[outputIndex++] = ENCODING_TABLE[( ( byte2 & 0x0F ) << 2 ) 143 | ( ( byte3 & 0xC0 ) >>> 6 )]; 144 output[outputIndex++] = ENCODING_TABLE[byte3 & 0x3F]; 145 } 146 147 if( paddingCharCount > 1 ) { 148 output[--outputIndex] = PADDING_BYTE; 149 } 150 if( paddingCharCount > 0 ) { 151 output[--outputIndex] = PADDING_BYTE; 152 } 153 154 return output; 155 } 156 } 157 158 | Popular Tags |