| 1 package gnu.kawa.xml; 2 3 4 5 public class Base64Binary extends BinaryObject 6 { 7 public Base64Binary (byte[] data) 8 { 9 this.data = data; 10 } 11 12 public static final String ENCODING 13 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 14 15 public static Base64Binary valueOf (String str) 16 { 17 return new Base64Binary(str); 18 } 19 20 public Base64Binary (String str) 21 { 22 int len = str.length(); 23 int blen = 0; 24 for (int i = 0; i < len; i++) 25 { 26 char ch = str.charAt(i); 27 if (! Character.isWhitespace(ch) && ch != '=') 28 blen++; 29 } 30 blen = (3 * blen) / 4; 31 byte[] bytes = new byte[blen]; 32 33 int value = 0; 34 int buffered = 0; 35 int padding = 0; 36 blen = 0; 37 for (int i = 0; i < len; i++) 38 { 39 char ch = str.charAt(i); 40 int v; 41 if (ch >= 'A' && ch <= 'Z') 42 v = ch - 'A'; 43 else if (ch >= 'a' && ch <= 'z') 44 v = ch - 'a' + 26; 45 else if (ch >= '0' && ch <= '9') 46 v = ch - '0' + 52; 47 else if (ch == '+') 48 v = 62; 49 else if (ch == '/') 50 v = 63; 51 else if (Character.isWhitespace(ch)) 52 continue; 53 else if (ch == '=') 54 { 55 padding++; 56 continue; 57 } 58 else 59 v = -1; 60 if (v < 0 || padding > 0) 61 throw new IllegalArgumentException ("illegal character in base64Binary string at position "+i); 62 value = (value << 6) + v; 63 buffered++; 64 if (buffered == 4) 65 { 66 bytes[blen++] = (byte) (value >> 16); 67 bytes[blen++] = (byte) (value >> 8); 68 bytes[blen++] = (byte) (value); 69 buffered = 0; 70 } 71 86 } 87 if (buffered+padding > 0 88 ? (buffered + padding != 4 89 || (value & ((1 << padding) - 1)) != 0 90 || blen + 3 - padding != bytes.length) 91 : blen != bytes.length) 92 throw new IllegalArgumentException (); 93 switch (padding) 94 { 95 case 1: 96 bytes[blen++] = (byte) (value << 10); 97 bytes[blen++] = (byte) (value >> 2); 98 break; 99 case 2: 100 bytes[blen++] = (byte) (value >> 4); 101 break; 102 } 103 this.data = bytes; 105 } 106 107 public StringBuffer toString (StringBuffer sbuf) 108 { 109 byte[] bb = data; 110 int len = bb.length; 111 int value = 0; 112 for (int i = 0; i < len; ) 113 { 114 byte b = bb[i]; 115 value = (value << 8) | (b & 0xFF); 116 i++; 117 if ((i % 3) == 0) 118 { 119 sbuf.append(ENCODING.charAt((value >> 18) & 63)); 120 sbuf.append(ENCODING.charAt((value >> 12) & 63)); 121 sbuf.append(ENCODING.charAt((value >> 6) & 63)); 122 sbuf.append(ENCODING.charAt(value & 63)); 123 } 124 } 125 switch (len % 3) 126 { 127 case 1: 128 sbuf.append(ENCODING.charAt((value >> 2) & 63)); 129 sbuf.append(ENCODING.charAt((value << 4) & 63)); 130 sbuf.append("=="); 131 break; 132 case 2: 133 sbuf.append(ENCODING.charAt((value >> 10) & 63)); 134 sbuf.append(ENCODING.charAt((value >> 4) & 63)); 135 sbuf.append(ENCODING.charAt((value << 2) & 63)); 136 sbuf.append('='); 137 break; 138 } 139 return sbuf; 140 } 141 142 public String toString () 143 { 144 return toString(new StringBuffer ()).toString(); 145 } 146 } 147 | Popular Tags |