一、前言
关于infoset-xproc源码包org.infoset.component.library.Base64Coder类,实现基于base64算法的字符串/字节数组encode加密、字符串/字节数组decode解密,详情参见源码说明部分。
二、源码说明
package org.infoset.component.library;@b@ @b@import java.io.PrintStream;@b@ @b@public class Base64Coder@b@{@b@ private static char[] map1 = new char[64];@b@ private static byte[] map2;@b@ @b@ public static String encode(String s)@b@ {@b@ return new String(encode(s.getBytes()));@b@ }@b@ @b@ public static char[] encode(byte[] in)@b@ {@b@ return encode(in, 0, in.length); }@b@ @b@ public static char[] encode(byte[] in, int pos, int iLen) {@b@ int oDataLen = (iLen * 4 + 2) / 3;@b@ int oLen = (iLen + 2) / 3 * 4;@b@ char[] out = new char[oLen];@b@ int ip = pos;@b@ int op = pos;@b@ while (ip < iLen) {@b@ int i0 = in[(ip++)] & 0xFF;@b@ int i1 = (ip < iLen) ? in[(ip++)] & 0xFF : 0;@b@ int i2 = (ip < iLen) ? in[(ip++)] & 0xFF : 0;@b@ int o0 = i0 >>> 2;@b@ int o1 = (i0 & 0x3) << 4 | i1 >>> 4;@b@ int o2 = (i1 & 0xF) << 2 | i2 >>> 6;@b@ int o3 = i2 & 0x3F;@b@ out[(op++)] = map1[o0];@b@ out[(op++)] = map1[o1];@b@ out[op] = ((op < oDataLen) ? map1[o2] : '='); ++op;@b@ out[op] = ((op < oDataLen) ? map1[o3] : '='); ++op; }@b@ return out;@b@ }@b@ @b@ public static String decode(String s)@b@ {@b@ return new String(decode(s.toCharArray()));@b@ }@b@ @b@ public static byte[] decode(char[] in)@b@ {@b@ int iLen = in.length;@b@ if (iLen % 4 != 0) throw new IllegalArgumentException("Length of Base64 encoded input string is not a multiple of 4.");@b@ for (; (iLen > 0) && (in[(iLen - 1)] == '='); --iLen);@b@ int oLen = iLen * 3 / 4;@b@ byte[] out = new byte[oLen];@b@ int ip = 0;@b@ int op = 0;@b@ while (ip < iLen) {@b@ int i0 = in[(ip++)];@b@ int i1 = in[(ip++)];@b@ int i2 = (ip < iLen) ? in[(ip++)] : 65;@b@ int i3 = (ip < iLen) ? in[(ip++)] : 65;@b@ if ((i0 > 127) || (i1 > 127) || (i2 > 127) || (i3 > 127))@b@ throw new IllegalArgumentException("Illegal character in Base64 encoded data.");@b@ int b0 = map2[i0];@b@ int b1 = map2[i1];@b@ int b2 = map2[i2];@b@ int b3 = map2[i3];@b@ if ((b0 < 0) || (b1 < 0) || (b2 < 0) || (b3 < 0))@b@ throw new IllegalArgumentException("Illegal character in Base64 encoded data.");@b@ int o0 = b0 << 2 | b1 >>> 4;@b@ int o1 = (b1 & 0xF) << 4 | b2 >>> 2;@b@ int o2 = (b2 & 0x3) << 6 | b3;@b@ out[(op++)] = (byte)o0;@b@ if (op < oLen) out[(op++)] = (byte)o1;@b@ if (op < oLen) out[(op++)] = (byte)o2; @b@ }@b@ return out; }@b@ @b@ public static void main(String[] args) {@b@ for (int i = 0; i < args.length; ++i)@b@ System.out.println(decode(args[i]));@b@ }@b@ @b@ static@b@ {@b@ int i = 0;@b@ for (char c = 'A'; c <= 'Z'; ) { map1[(i++)] = c; c = (char)(c + '\1'); }@b@ for (c = 'a'; c <= 'z'; ) { map1[(i++)] = c; c = (char)(c + '\1'); }@b@ for (c = '0'; c <= '9'; ) { map1[(i++)] = c; c = (char)(c + '\1'); }@b@ map1[(i++)] = '+'; map1[(i++)] = '/';@b@ @b@ map2 = new byte[128];@b@ @b@ for (i = 0; i < map2.length; ) { map2[i] = -1; ++i; }@b@ for (i = 0; i < 64; ) { map2[map1[i]] = (byte)i; ++i;@b@ }@b@ }@b@}