Google Base64可以搜到相关原理和许多实现。
下面是我的实现,和SUN公司提供的参考实现。
1 public class Base64 {
2 static String base64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
3
4 /**
5 * 编码原理:将3个字节转换成4个字节( (3 X 8) = 24 = (4 X 6) )
6 * 先读入3个字节,每读一个字节,左移8位,再右移四次,每次6位,这样就有4个字节了
7 *
8 * @param data
9 * @return 编码后的Base64字符串
10 */
11 public static String Base64Encode(byte[] data) {
12 StringBuilder builder = new StringBuilder();
13 int[] temp = new int[4];
14 int len = data.length - data.length % 3;
15 for (int i = 0; i < len; i += 3) {
16 int goal = 0;
17 for (int j = 0; j < 3; j++) {
18 goal <<= 8;
19 goal |= (data[i + j] & 0xff);
20 }
21 for (int k = 0; k < 4; k++) {
22 temp[k] = goal & 0x3f;
23 goal >>= 6;
24 }
25 for (int k = 3; k >= 0; k--) {
26 builder.append(base64_alphabet.charAt(temp[k]));
27 }
28 }
29 int index;
30 switch (data.length % 3) {
31 case 1:
32 index = data[data.length - 1] >> 2;
33 builder.append(base64_alphabet.charAt(index));
34 index = (data[data.length - 1] & 0x03) << 4;
35 builder.append(base64_alphabet.charAt(index));
36 builder.append("==");
37 break;
38 case 2:
39 index = data[data.length - 1 - 1] >> 2;
40 builder.append(base64_alphabet.charAt(index));
41 index = (data[data.length - 1 - 1] & 0x03) << 4
42 | data[data.length - 1] >> 4;
43 builder.append(base64_alphabet.charAt(index));
44 index = (data[data.length - 1] & 0x0f) << 2;
45 builder.append(base64_alphabet.charAt(index));
46 builder.append('=');
47 break;
48 }
49 return builder.toString();
50 }
51
52 /**
53 * 解码原理:将4个字节转换成3个字节. 先读入4个6位(用或运算),每次左移6位,再右移3次,每次8位.
54 *
55 * @param data
56 * 需解码的Base64字符串。
57 * @return byte[]-解码出的字节数组
58 */
59 public static byte[] Base64Decode(String data) {
60 char[] chArray = data.toCharArray();
61 int len = chArray.length;
62 byte[] result = new byte[len * 3 / 4];
63 for (int i = 0, res_i = 0; i < len; i += 4, res_i += 3) {
64 int goal = 0;
65 int index = 0;
66 for (int k = 0; k < 4; k++) {
67 index = base64_alphabet.indexOf(chArray[i + k]);
68 goal <<= 6;
69 goal |= index;
70 }
71 for (int j = 2; j >= 0; j--) {
72 result[res_i + j] = (byte) goal;
73 goal >>= 8;
74 }
75 }
76 // 等号=的处理
77 if (chArray[len - 1] != '=')
78 return result;
79 else if (chArray[len - 2] == '=')
80 return Arrays.copyOf(result, result.length - 2);
81 else
82 return Arrays.copyOf(result, result.length - 1);
83
84 }
85 // 将 s 进行 BASE64 编码
86 public static String getBASE64(String s) {
87 if (s == null)
88 return null;
89 return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
90 }
91
92 // 将 BASE64 编码的字符串 s 进行解码
93 public static String getFromBASE64(String s) {
94 if (s == null)
95 return null;
96 BASE64Decoder decoder = new BASE64Decoder();
97 try {
98 byte[] b = decoder.decodeBuffer(s);
99 return new String(b);
100 } catch (Exception e) {
101 return null;
102 }
103 }
104 }