1 25 package com.scalagent.ksoap.marshal; 26 27 import java.io.*; 28 29 public class Base64 { 30 static final char[] charTab = 31 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); 32 33 public static String encode(byte [] data) { 34 return encode (data,0,data.length,null).toString(); 35 } 36 37 public static StringBuffer encode(byte [] data, int start, int len, StringBuffer buf) { 38 if (buf == null) 39 buf = new StringBuffer (data.length * 3 / 2); 40 41 int end = len - 3; 42 int i = start; 43 int n = 0; 44 45 while (i <= end) { 46 int d = ((((int) data[i]) & 0x0ff) << 16) 47 | ((((int) data[i+1]) & 0x0ff) << 8) 48 | (((int) data[i+2]) & 0x0ff); 49 buf.append(charTab[(d >> 18) & 63]); 50 buf.append(charTab[(d >> 12) & 63]); 51 buf.append(charTab[(d >> 6) & 63]); 52 buf.append(charTab[d & 63]); 53 i += 3; 54 if (n++ >= 14) { 55 n = 0; 56 buf.append("\r\n"); 57 } 58 } 59 60 if (i == start + len - 2) { 61 int d = ((((int) data[i]) & 0x0ff) << 16) 62 | ((((int) data[i+1]) & 255) << 8); 63 buf.append(charTab[(d >> 18) & 63]); 64 buf.append(charTab[(d >> 12) & 63]); 65 buf.append(charTab[(d >> 6) & 63]); 66 buf.append("="); 67 } else if (i == start + len - 1) { 68 int d = (((int) data[i]) & 0x0ff) << 16; 69 buf.append(charTab[(d >> 18) & 63]); 70 buf.append(charTab[(d >> 12) & 63]); 71 buf.append("=="); 72 } 73 return buf; 74 } 75 76 static int decode(char c) { 77 if (c >= 'A' && c <= 'Z') 78 return ((int) c) - 65; 79 else if (c >= 'a' && c <= 'z') 80 return ((int) c) - 97 + 26; 81 else if (c >= '0' && c <= '9') 82 return ((int) c) - 48 + 26 + 26; 83 else 84 switch (c) { 85 case '+': return 62; 86 case '/': return 63; 87 case '=': return 0; 88 default: 89 throw new RuntimeException ("unexpected code: "+c); 90 } 91 } 92 93 public static byte [] decode(String s) { 94 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 95 decode(s,bos); 96 return bos.toByteArray(); 97 } 98 99 public static void decode(String s, ByteArrayOutputStream bos) { 100 int i = 0; 101 int len = s.length(); 102 103 while (true) { 104 while (i < len && s.charAt(i) <= ' ') i++; 105 if (i == len) break; 106 int tri = (decode(s.charAt(i)) << 18) 107 + (decode(s.charAt(i+1)) << 12) 108 + (decode(s.charAt(i+2)) << 6) 109 + (decode(s.charAt(i+3))); 110 bos.write((tri >> 16) & 255); 111 if (s.charAt (i+2) == '=') break; 112 bos.write((tri >> 8) & 255); 113 if (s.charAt (i+3) == '=') break; 114 bos.write(tri & 255); 115 i += 4; 116 } 117 } 118 } 119 | Popular Tags |