1 36 package org.ungoverned.oscar.util; 37 38 import java.io.*; 39 40 public class Util 41 { 42 private static final byte encTab[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 43 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 44 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 45 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 46 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 47 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f }; 48 49 private static final byte decTab[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 50 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 51 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 52 -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, 53 -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 54 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 55 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 56 48, 49, 50, 51, -1, -1, -1, -1, -1 }; 57 58 public static String base64Encode(String s) throws IOException 59 { 60 return encode(s.getBytes(), 0); 61 } 62 63 69 public static String encode(byte[] in, int len) throws IOException 70 { 71 ByteArrayOutputStream baos = null; 72 ByteArrayInputStream bais = null; 73 try 74 { 75 baos = new ByteArrayOutputStream(); 76 bais = new ByteArrayInputStream(in); 77 encode(bais, baos, len); 78 return (new String (baos.toByteArray())); 80 } 81 finally 82 { 83 if (baos != null) 84 { 85 baos.close(); 86 } 87 if (bais != null) 88 { 89 bais.close(); 90 } 91 } 92 } 93 94 public static void encode(InputStream in, OutputStream out, int len) 95 throws IOException 96 { 97 98 if (len % 4 != 0) 100 { 101 throw new IllegalArgumentException ("Length must be a multiple of 4"); 102 } 103 104 int bits = 0; 106 int nbits = 0; 107 int nbytes = 0; 108 int b; 109 110 while ((b = in.read()) != -1) 111 { 112 bits = (bits << 8) | b; 113 nbits += 8; 114 while (nbits >= 6) 115 { 116 nbits -= 6; 117 out.write(encTab[0x3f & (bits >> nbits)]); 118 nbytes++; 119 if (len != 0 && nbytes >= len) 121 { 122 out.write(0x0d); 123 out.write(0x0a); 124 nbytes -= len; 125 } 126 } 127 } 128 129 switch (nbits) 130 { 131 case 2: 132 out.write(encTab[0x3f & (bits << 4)]); 133 out.write(0x3d); out.write(0x3d); 135 break; 136 case 4: 137 out.write(encTab[0x3f & (bits << 2)]); 138 out.write(0x3d); 139 break; 140 } 141 142 if (len != 0) 143 { 144 if (nbytes != 0) 145 { 146 out.write(0x0d); 147 out.write(0x0a); 148 } 149 out.write(0x0d); 150 out.write(0x0a); 151 } 152 } 153 } | Popular Tags |