1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import java.nio.ByteBuffer;
|
---|
5 |
|
---|
6 | public final class Base64 {
|
---|
7 |
|
---|
8 | private Base64() {
|
---|
9 | // Hide default constructor for utils classes
|
---|
10 | }
|
---|
11 |
|
---|
12 | private static String encDefault = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
---|
13 | private static String encUrlSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
---|
14 |
|
---|
15 | public static String encode(String s) {
|
---|
16 | return encode(s, false);
|
---|
17 | }
|
---|
18 |
|
---|
19 | public static String encode(String s, boolean urlsafe) {
|
---|
20 | StringBuilder out = new StringBuilder();
|
---|
21 | String enc = urlsafe ? encUrlSafe : encDefault;
|
---|
22 | for (int i = 0; i < (s.length()+2)/3; ++i) {
|
---|
23 | int l = Math.min(3, s.length()-i*3);
|
---|
24 | String buf = s.substring(i*3, i*3+l);
|
---|
25 | out.append(enc.charAt(buf.charAt(0)>>2));
|
---|
26 | out.append(enc.charAt(
|
---|
27 | (buf.charAt(0) & 0x03) << 4 |
|
---|
28 | (l==1?
|
---|
29 | 0:
|
---|
30 | (buf.charAt(1) & 0xf0) >> 4)));
|
---|
31 | out.append(l>1?enc.charAt((buf.charAt(1) & 0x0f) << 2 | (l==2?0:(buf.charAt(2) & 0xc0) >> 6)):'=');
|
---|
32 | out.append(l>2?enc.charAt(buf.charAt(2) & 0x3f):'=');
|
---|
33 | }
|
---|
34 | return out.toString();
|
---|
35 | }
|
---|
36 |
|
---|
37 | public static String encode(ByteBuffer s) {
|
---|
38 | return encode(s, false);
|
---|
39 | }
|
---|
40 |
|
---|
41 | public static String encode(ByteBuffer s, boolean urlsafe) {
|
---|
42 | StringBuilder out = new StringBuilder();
|
---|
43 | String enc = urlsafe ? encUrlSafe : encDefault;
|
---|
44 | // Read 3 bytes at a time.
|
---|
45 | for (int i = 0; i < (s.limit()+2)/3; ++i) {
|
---|
46 | int l = Math.min(3, s.limit()-i*3);
|
---|
47 | int byte0 = s.get() & 0xff;
|
---|
48 | int byte1 = l>1? s.get() & 0xff : 0;
|
---|
49 | int byte2 = l>2? s.get() & 0xff : 0;
|
---|
50 |
|
---|
51 | out.append(enc.charAt(byte0>>2));
|
---|
52 | out.append(enc.charAt(
|
---|
53 | (byte0 & 0x03) << 4 |
|
---|
54 | (l==1?
|
---|
55 | 0:
|
---|
56 | (byte1 & 0xf0) >> 4)));
|
---|
57 | out.append(l>1?enc.charAt((byte1 & 0x0f) << 2 | (l==2?0:(byte2 & 0xc0) >> 6)):'=');
|
---|
58 | out.append(l>2?enc.charAt(byte2 & 0x3f):'=');
|
---|
59 | }
|
---|
60 | return out.toString();
|
---|
61 | }
|
---|
62 | }
|
---|