1 36 package org.columba.ristretto.coder; 37 38 import java.io.FilterInputStream ; 39 import java.io.IOException ; 40 import java.io.InputStream ; 41 42 50 public class Base64DecoderInputStream extends FilterInputStream { 51 52 54 private static byte[] table = 55 { 56 000, 57 000, 58 000, 59 000, 60 000, 61 000, 62 000, 63 000, 64 000, 65 000, 66 000, 67 000, 68 000, 69 000, 70 000, 71 000, 72 000, 73 000, 74 000, 75 000, 76 000, 77 000, 78 000, 79 000, 80 000, 81 000, 82 000, 83 000, 84 000, 85 000, 86 000, 87 000, 88 000, 89 000, 90 000, 91 000, 92 000, 93 000, 94 000, 95 000, 96 000, 97 000, 98 000, 99 62, 100 000, 101 000, 102 000, 103 63, 104 52, 105 53, 106 54, 55, 56, 57, 58, 59, 60, 61, 000, 000, 000, 0, 000, 000, 000, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 000, 000, 000, 000, 000, 000, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 000, 000, 000, 000, 000 }; 116 private int[] outBytes; 117 private byte[] inBytes; 118 private int pos; 119 private int available; 120 121 126 public Base64DecoderInputStream(InputStream in) { 127 super(new CRLFFilterInputStream(in)); 128 outBytes = new int[3]; 129 inBytes = new byte[4]; 130 } 131 132 139 private int readNextPack() throws IOException { 140 int[] lookedUp = new int[4]; 141 142 int read = in.read(inBytes); 144 145 if (read != 4) 146 return -1; 147 148 lookedUp[0] = table[inBytes[0]]; 149 lookedUp[1] = table[inBytes[1]]; 150 lookedUp[2] = table[inBytes[2]]; 151 lookedUp[3] = table[inBytes[3]]; 152 153 outBytes[0] = 0x0ff & ((lookedUp[0] << 2) | (lookedUp[1] >> 4)); 154 outBytes[1] = 0x0ff & ((lookedUp[1] << 4) | (lookedUp[2] >> 2)); 155 outBytes[2] = 0x0ff & ((lookedUp[2] << 6) | (lookedUp[3])); 156 157 158 if (inBytes[2] == 61) { 160 return 1; 161 } 162 if (inBytes[3] == 61) { 163 return 2; 164 } 165 166 return 3; 167 } 168 169 172 public int read() throws IOException { 173 if( pos == available ) { 175 available = readNextPack(); 176 pos = 0; 177 } 178 179 if( available == -1) return -1; 181 182 return outBytes[pos++]; 184 } 185 186 189 public int read(byte[] arg0, int arg1, int arg2) throws IOException { 190 int next; 191 for( int i=0; i<arg2; i++) { 192 next = read(); 193 if( next == -1 ) { 194 if( i == 0 ) { 195 return -1; 196 } else { 197 return i; 198 } 199 } 200 arg0[arg1+i] = (byte) next; 201 } 202 return arg2; 203 } 204 205 } | Popular Tags |