1 package org.rpi.plugin.lastfm;
2 public class Base64 {
3
4 private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
5
6 private static int[] toInt = new int[128];
7
8 static {
9 for(int i=0; i< ALPHABET.length; i++){
10 toInt[ALPHABET[i]]= i;
11 }
12 }
13
14
15
16
17
18
19
20 public static String encode(byte[] buf){
21 int size = buf.length;
22 char[] ar = new char[((size + 2) / 3) * 4];
23 int a = 0;
24 int i=0;
25 while(i < size){
26 byte b0 = buf[i++];
27 byte b1 = (i < size) ? buf[i++] : 0;
28 byte b2 = (i < size) ? buf[i++] : 0;
29
30 int mask = 0x3F;
31 ar[a++] = ALPHABET[(b0 >> 2) & mask];
32 ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
33 ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
34 ar[a++] = ALPHABET[b2 & mask];
35 }
36 switch(size % 3){
37 case 1: ar[--a] = '=';
38 case 2: ar[--a] = '=';
39 }
40 return new String(ar);
41 }
42
43
44
45
46
47
48
49 public static byte[] decode(String s){
50 int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0;
51 byte[] buffer = new byte[s.length()*3/4 - delta];
52 int mask = 0xFF;
53 int index = 0;
54 for(int i=0; i< s.length(); i+=4){
55 int c0 = toInt[s.charAt( i )];
56 int c1 = toInt[s.charAt( i + 1)];
57 buffer[index++]= (byte)(((c0 << 2) | (c1 >> 4)) & mask);
58 if(index >= buffer.length){
59 return buffer;
60 }
61 int c2 = toInt[s.charAt( i + 2)];
62 buffer[index++]= (byte)(((c1 << 4) | (c2 >> 2)) & mask);
63 if(index >= buffer.length){
64 return buffer;
65 }
66 int c3 = toInt[s.charAt( i + 3 )];
67 buffer[index++]= (byte)(((c2 << 6) | c3) & mask);
68 }
69 return buffer;
70 }
71
72 }