1 4 package de.nava.informa.utils; 5 6 import java.io.IOException ; 7 import java.io.FilterInputStream ; 8 import java.io.*; 9 10 26 class Base64Decoder extends FilterInputStream { 27 28 private static final char[] chars = { 29 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 30 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 31 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 32 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 33 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 34 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', 35 '8', '9', '+', '/' 36 }; 37 38 private static final int[] ints = new int[128]; 40 static { 41 for (int i = 0; i < 64; i++) { 42 ints[chars[i]] = i; 43 } 44 } 45 46 private int charCount; 47 private int carryOver; 48 49 55 public Base64Decoder(InputStream in) { 56 super(in); 57 } 58 59 67 public int read() throws IOException { 68 int x; 70 do { 71 x = in.read(); 72 if (x == -1) { 73 return -1; 74 } 75 } while (Character.isWhitespace((char)x)); 76 charCount++; 77 78 if (x == '=') { 80 return -1; } 82 83 x = ints[x]; 85 86 int mode = (charCount - 1) % 4; 88 89 if (mode == 0) { 91 carryOver = x & 63; 92 return read(); 93 } 94 else if (mode == 1) { 97 int decoded = ((carryOver << 2) + (x >> 4)) & 255; 98 carryOver = x & 15; 99 return decoded; 100 } 101 else if (mode == 2) { 104 int decoded = ((carryOver << 4) + (x >> 2)) & 255; 105 carryOver = x & 3; 106 return decoded; 107 } 108 else if (mode == 3) { 110 int decoded = ((carryOver << 6) + x) & 255; 111 return decoded; 112 } 113 return -1; } 115 116 127 public int read(byte[] b, int off, int len) throws IOException { 128 int i; 130 for (i = 0; i < len; i++) { 131 int x = read(); 132 if (x == -1 && i == 0) { return -1; 134 } 135 else if (x == -1) { break; 137 } 138 b[off + i] = (byte) x; 139 } 140 return i; 141 } 142 143 149 public static String decode(String encoded) { 150 byte[] bytes = null; 151 try { 152 bytes = encoded.getBytes("8859_1"); 153 } 154 catch (UnsupportedEncodingException ignored) { } 155 156 Base64Decoder bin = new Base64Decoder( 157 new ByteArrayInputStream(bytes)); 158 159 ByteArrayOutputStream out = 160 new ByteArrayOutputStream((int) (bytes.length * 0.67)); 161 162 try { 163 byte[] buf = new byte[4 * 1024]; int bytesRead; 165 while ((bytesRead = bin.read(buf)) != -1) { 166 out.write(buf, 0, bytesRead); 167 } 168 out.close(); 169 170 return out.toString("8859_1"); 171 } 172 catch (IOException ignored) { 173 return null; 174 } 175 } 176 177 199 } 200 | Popular Tags |