-
Notifications
You must be signed in to change notification settings - Fork 1
/
Base64.java
63 lines (60 loc) · 2.29 KB
/
Base64.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//package com.charliemouse.cambozola.shared;
public class Base64 {
private static final char[] S_BASE64CHAR = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
};
private static final char S_BASE64PAD = '=';
/**
* Returns base64 representation of specified byte array.
* @param data The data to be encoded
* @return The base64 encoded data
*/
public static String encode(byte[] data) {
return encode(data, 0, data.length);
}
/**
* Returns base64 representation of specified byte array.
* @param data The data to be encoded
* @param off The offset within the data at which to start encoding
* @param len The length of the data to encode
* @return The base64 encoded data
*/
public static String encode(byte[] data, int off, int len) {
if (len <= 0) return "";
char[] out = new char[len/3*4+4];
int rindex = off;
int windex = 0;
int rest = len;
while (rest >= 3) {
int i = ((data[rindex]&0xff)<<16)
+((data[rindex+1]&0xff)<<8)
+(data[rindex+2]&0xff);
out[windex++] = S_BASE64CHAR[i>>18];
out[windex++] = S_BASE64CHAR[(i>>12)&0x3f];
out[windex++] = S_BASE64CHAR[(i>>6)&0x3f];
out[windex++] = S_BASE64CHAR[i&0x3f];
rindex += 3;
rest -= 3;
}
if (rest == 1) {
int i = data[rindex]&0xff;
out[windex++] = S_BASE64CHAR[i>>2];
out[windex++] = S_BASE64CHAR[(i<<4)&0x3f];
out[windex++] = S_BASE64PAD;
out[windex++] = S_BASE64PAD;
} else if (rest == 2) {
int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff);
out[windex++] = S_BASE64CHAR[i>>10];
out[windex++] = S_BASE64CHAR[(i>>4)&0x3f];
out[windex++] = S_BASE64CHAR[(i<<2)&0x3f];
out[windex++] = S_BASE64PAD;
}
return new String(out, 0, windex);
}
}