1 28 package org.jvyamlb.util; 29 30 33 public class Base64Coder { 34 private final static char[] map1 = new char[64]; 36 static { 37 int i=0; 38 for(char c='A'; c<='Z'; c++) map1[i++] = c; 39 for(char c='a'; c<='z'; c++) map1[i++] = c; 40 for(char c='0'; c<='9'; c++) map1[i++] = c; 41 map1[i++] = '+'; map1[i++] = '/'; 42 } 43 44 private final static byte[] map2 = new byte[128]; 46 static { 47 for(int i=0; i<map2.length; i++) map2[i] = -1; 48 for(int i=0; i<64; i++) map2[map1[i]] = (byte)i; 49 } 50 51 57 public static String encode(final String s) { 58 return new String (encode(s.getBytes())); 59 } 60 61 67 public static char[] encode(final byte[] in) { 68 int iLen = in.length; 69 int oDataLen = (iLen*4+2)/3; int oLen = ((iLen+2)/3)*4; char[] out = new char[oLen]; 72 int ip = 0; 73 int op = 0; 74 while (ip < iLen) { 75 int i0 = in[ip++] & 0xff; 76 int i1 = ip < iLen ? in[ip++] & 0xff : 0; 77 int i2 = ip < iLen ? in[ip++] & 0xff : 0; 78 int o0 = i0 >>> 2; 79 int o1 = ((i0 & 3) << 4) | (i1 >>> 4); 80 int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); 81 int o3 = i2 & 0x3F; 82 out[op++] = map1[o0]; 83 out[op++] = map1[o1]; 84 out[op] = op < oDataLen ? map1[o2] : '='; op++; 85 out[op] = op < oDataLen ? map1[o3] : '='; op++; } 86 return out; 87 } 88 89 96 public static byte[] decode(final byte[] in) { 97 int iLen = in.length; 98 if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); 99 while (iLen > 0 && in[iLen-1] == '=') iLen--; 100 int oLen = (iLen*3) / 4; 101 byte[] out = new byte[oLen]; 102 int ip = 0; 103 int op = 0; 104 while (ip < iLen) { 105 int i0 = in[ip++]; 106 int i1 = in[ip++]; 107 int i2 = ip < iLen ? in[ip++] : 'A'; 108 int i3 = ip < iLen ? in[ip++] : 'A'; 109 if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) 110 throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); 111 int b0 = map2[i0]; 112 int b1 = map2[i1]; 113 int b2 = map2[i2]; 114 int b3 = map2[i3]; 115 if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) 116 throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); 117 int o0 = ( b0 <<2) | (b1>>>4); 118 int o1 = ((b1 & 0xf)<<4) | (b2>>>2); 119 int o2 = ((b2 & 3)<<6) | b3; 120 out[op++] = (byte)o0; 121 if (op<oLen) out[op++] = (byte)o1; 122 if (op<oLen) out[op++] = (byte)o2; } 123 return out; 124 } 125 } 126 | Popular Tags |