1 19 20 package gnu.mail.util; 21 22 import java.io.*; 23 24 37 public class Base64InputStream 38 extends FilterInputStream 39 { 40 41 private byte[] buffer; 42 private int buflen; 43 private int index; 44 private byte[] decodeBuf; 45 46 private static final char[] src = 47 { 48 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 49 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 50 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 51 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 52 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 53 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', 54 '8', '9', '+', '/' 55 }; 56 private static final byte[] dst; 57 58 private static final int LF = 10, CR = 13, EQ = 61; 59 60 static 61 { 62 dst = new byte[256]; 63 for (int i = 0; i<255; i++) 64 dst[i] = -1; 65 for (int i = 0; i<src.length; i++) 66 dst[src[i]] = (byte)i; 67 68 } 69 70 75 public Base64InputStream(InputStream in) 76 { 77 super(in); 78 decodeBuf = new byte[4]; 79 buffer = new byte[3]; 80 } 81 82 85 public int read() 86 throws IOException 87 { 88 if (index>=buflen) 89 { 90 decode(); 91 if (buflen==0) 92 return -1; 93 index = 0; 94 } 95 return buffer[index++] & 0xff; 96 } 97 98 102 public int read(byte[] b, int off, int len) 103 throws IOException 104 { 105 try 106 { 107 int l = 0; 108 for (; l<len; l++) 109 { 110 int c; 111 if ((c=read())==-1) 112 { 113 if (l==0) 114 l = -1; 115 break; 116 } 117 b[off+l] = (byte)c; 118 } 119 return l; 120 } 121 catch (IOException e) 122 { 123 return -1; 124 } 125 } 126 127 132 public int available() 133 throws IOException 134 { 135 return (in.available()*3)/4+(buflen-index); 136 } 137 138 private void decode() 139 throws IOException 140 { 141 buflen = 0; 142 int c; 143 do 144 { 145 c = in.read(); 146 if (c==-1) 147 return; 148 } 149 while (c==LF || c==CR); 150 decodeBuf[0] = (byte)c; 151 int j = 3, l; 152 for (int k=1; (l=in.read(decodeBuf, k, j))!=j; k += l) 153 { 154 if (l==-1) 155 throw new IOException("Base64 encoding error"); 156 j -= l; 157 } 158 159 byte b0 = dst[decodeBuf[0] & 0xff]; 160 byte b2 = dst[decodeBuf[1] & 0xff]; 161 buffer[buflen++] = (byte)(b0<<2 & 0xfc | b2>>>4 & 0x3); 162 if (decodeBuf[2]!=EQ) 163 { 164 b0 = b2; 165 b2 = dst[decodeBuf[2] & 0xff]; 166 buffer[buflen++] = (byte)(b0<<4 & 0xf0 | b2>>>2 & 0xf); 167 if (decodeBuf[3]!=EQ) 168 { 169 byte b1 = b2; 170 b2 = dst[decodeBuf[3] & 0xff]; 171 buffer[buflen++] = (byte)(b1<<6 & 0xc0 | b2 & 0x3f); 172 } 173 } 174 } 175 176 } 177 | Popular Tags |