1 18 package org.apache.batik.util; 19 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 23 48 49 public class Base64DecodeStream extends InputStream { 50 51 InputStream src; 52 53 public Base64DecodeStream(InputStream src) { 54 this.src = src; 55 } 56 57 private final static byte pem_array[] = new byte[256]; 58 static { 59 for (int i=0; i<pem_array.length; i++) 60 pem_array[i] = -1; 61 62 int idx = 0; 63 for (char c='A'; c<='Z'; c++) { 64 pem_array[c] = (byte)idx++; 65 } 66 for (char c='a'; c<='z'; c++) { 67 pem_array[c] = (byte)idx++; 68 } 69 70 for (char c='0'; c<='9'; c++) { 71 pem_array[c] = (byte)idx++; 72 } 73 74 pem_array['+'] = (byte)idx++; 75 pem_array['/'] = (byte)idx++; 76 } 77 78 public boolean markSupported() { return false; } 79 80 public void close() 81 throws IOException { 82 EOF = true; 83 } 84 85 public int available() 86 throws IOException { 87 return 3-out_offset; 88 } 89 90 byte decode_buffer[] = new byte[4]; 91 byte out_buffer[] = new byte[3]; 92 int out_offset = 3; 93 boolean EOF = false; 94 95 public int read() throws IOException { 96 97 if (out_offset == 3) { 98 if (EOF || getNextAtom()) { 99 EOF = true; 100 return -1; 101 } 102 } 103 104 return ((int)out_buffer[out_offset++])&0xFF; 105 } 106 107 public int read(byte []out, int offset, int len) 108 throws IOException { 109 110 int idx = 0; 111 while (idx < len) { 112 if (out_offset == 3) { 113 if (EOF || getNextAtom()) { 114 EOF = true; 115 if (idx == 0) return -1; 116 else return idx; 117 } 118 } 119 120 out[offset+idx] = out_buffer[out_offset++]; 121 122 idx++; 123 } 124 return idx; 125 } 126 127 final boolean getNextAtom() throws IOException { 128 int count, a, b, c, d; 129 130 int off = 0; 131 while(off != 4) { 132 count = src.read(decode_buffer, off, 4-off); 133 if (count == -1) 134 return true; 135 136 int in=off, out=off; 137 while(in < off+count) { 138 if ((decode_buffer[in] != '\n') && 139 (decode_buffer[in] != '\r') && 140 (decode_buffer[in] != ' ')) 141 decode_buffer[out++] = decode_buffer[in]; 142 in++; 143 } 144 145 off = out; 146 } 147 148 a = pem_array[((int)decode_buffer[0])&0xFF]; 149 b = pem_array[((int)decode_buffer[1])&0xFF]; 150 c = pem_array[((int)decode_buffer[2])&0xFF]; 151 d = pem_array[((int)decode_buffer[3])&0xFF]; 152 153 out_buffer[0] = (byte)((a<<2) | (b>>>4)); 154 out_buffer[1] = (byte)((b<<4) | (c>>>2)); 155 out_buffer[2] = (byte)((c<<6) | d ); 156 157 if (decode_buffer[3] != '=') { 158 out_offset=0; 160 } else if (decode_buffer[2] == '=') { 161 out_buffer[2] = out_buffer[0]; 163 out_offset = 2; 164 EOF=true; 165 } else { 166 out_buffer[2] = out_buffer[1]; 168 out_buffer[1] = out_buffer[0]; 169 out_offset = 1; 170 EOF=true; 171 } 172 173 return false; 174 } 175 } 176 | Popular Tags |