Java itself is a toolkit that provides BASE64 encoding, and when the project is done by itself, it is recorded here:
1 / ** Base64 encoded array * /
2 private static final String base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
3
4 / **
5 * Base64 encoding
6 * @param str string to be encoded
7 * @return
8 */
9 public static String base64encode (String str) {
10 String out = "";
11 int i = 0;
12 int len = str.length ();
13 int c1, c2, c3;
14 while (i <len) {
15 c1 = str.charAt (i ++) & 0xff;
16 if (i == len) {
17 out + = base64EncodeChars.charAt (c1 >> 2);
18 out + = base64EncodeChars.charAt ((c1 & 0x3) << 4);
19 out + = "==";
20 break;
twenty one }
22 c2 = str.charAt (i ++);
23 if (i == len) {
24 out + = base64EncodeChars.charAt (c1 >> 2);
25 out + = base64EncodeChars.charAt (((c1 & 0x3) << 4)
26 | ((c2 & 0xF0) >> 4));
27 out + = base64EncodeChars.charAt ((c2 & 0xF) << 2);
28 out + = "=";
29 break;
30}
31 c3 = str.charAt (i ++);
32 out + = base64EncodeChars.charAt (c1 >> 2);
33 out + = base64EncodeChars.charAt (((c1 & 0x3) << 4)
34 | ((c2 & 0xF0) >> 4));
35 out + = base64EncodeChars.charAt (((c2 & 0xF) << 2)
36 | ((c3 & 0xC0) >> 6));
37 out + = base64EncodeChars.charAt (c3 & 0x3F);
38}
39 return out;
40}
If you want to generate a URL-safe Base64 encoding, you need to replace the "+" inside with "-" and replace "/" with "_"
1 /**
2 * Convert Base64 encoding to URL-safe Base64 encoding
3 * @param str Base64 encoded string
4 * @return
5 * /
6 private static String safe64 (String str) {
7 String result = str.replace ("+", "-");
8 return result.replace ("/", "_");
9 }
/** BASE64 Encoded Array */
private static final String Base64encodechars = "Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789-_";
Java implementation of BASE64 encoding