-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathBase91.java
108 lines (94 loc) · 2.61 KB
/
Base91.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cryptography.encoding.base91;
import java.io.ByteArrayOutputStream;
import cryptography.Mode;
public class Base91 {
private static final byte[] ENCODING_TABLE;
private static final byte[] DECODING_TABLE;
private static final int BASE;
private static final float AVERAGE_ENCODING_RATIO = 1.2297f;
public static void main(String[] args) {
}
static {
String ts = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~\"";
ENCODING_TABLE = ts.getBytes();
BASE = ENCODING_TABLE.length;
DECODING_TABLE = new byte[256];
for (int i = 0; i < 256; ++i) {
DECODING_TABLE[i] = -1;
}
for (int i = 0; i < BASE; ++i) {
DECODING_TABLE[ENCODING_TABLE[i]] = (byte) i;
}
}
public static String base91(String input, Mode mode) {
StringBuilder sb = new StringBuilder();
byte[] data = input.getBytes();
if (mode == Mode.ENCODE) {
try {
int estimatedSize = (int) Math.ceil(data.length * AVERAGE_ENCODING_RATIO);
ByteArrayOutputStream output = new ByteArrayOutputStream(estimatedSize);
int ebq = 0;
int en = 0;
for (int i = 0; i < data.length; ++i) {
ebq |= (data[i] & 255) << en;
en += 8;
if (en > 13) {
int ev = ebq & 8191;
if (ev > 88) {
ebq >>= 13;
en -= 13;
} else {
ev = ebq & 16383;
ebq >>= 14;
en -= 14;
}
output.write(ENCODING_TABLE[ev % BASE]);
output.write(ENCODING_TABLE[ev / BASE]);
}
}
if (en > 0) {
output.write(ENCODING_TABLE[ebq % BASE]);
if (en > 7 || ebq > 90) {
output.write(ENCODING_TABLE[ebq / BASE]);
}
}
sb.append(new String(output.toByteArray()));
} catch (ArrayIndexOutOfBoundsException e) {
return "Error; " + e.toString();
}
}
if (mode == Mode.DECODE) {
try {
int dbq = 0;
int dn = 0;
int dv = -1;
int estimatedSize = Math.round(data.length / AVERAGE_ENCODING_RATIO);
ByteArrayOutputStream output = new ByteArrayOutputStream(estimatedSize);
for (int i = 0; i < data.length; ++i) {
if (DECODING_TABLE[data[i]] == -1)
continue;
if (dv == -1)
dv = DECODING_TABLE[data[i]];
else {
dv += DECODING_TABLE[data[i]] * BASE;
dbq |= dv << dn;
dn += (dv & 8191) > 88 ? 13 : 14;
do {
output.write((byte) dbq);
dbq >>= 8;
dn -= 8;
} while (dn > 7);
dv = -1;
}
}
if (dv != -1) {
output.write((byte) (dbq | dv << dn));
}
sb.append(new String(output.toByteArray()));
} catch (ArrayIndexOutOfBoundsException e) {
return "Error; " + e.toString();
}
}
return sb.toString();
}
}