1 23 24 package org.objectweb.jonas.security.realm.lib; 25 26 36 public class Base64 { 37 38 41 private static char[] alphabet = 42 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" 43 .toCharArray(); 44 45 48 private static byte[] codes = new byte[256]; 49 50 static { 51 for (int i = 0; i < 256; i++) { 52 codes[i] = -1; 53 } 54 for (int i = 'A'; i <= 'Z'; i++) { 55 codes[i] = (byte) (i - 'A'); 56 } 57 for (int i = 'a'; i <= 'z'; i++) { 58 codes[i] = (byte) (26 + i - 'a'); 59 } 60 for (int i = '0'; i <= '9'; i++) { 61 codes[i] = (byte) (52 + i - '0'); 62 } 63 codes['+'] = 62; 64 codes['/'] = 63; 65 } 66 67 68 69 76 public static char[] encode(byte[] data) { 77 char[] out = new char[((data.length + 2) / 3) * 4]; 78 79 for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { 84 boolean quad = false; 85 boolean trip = false; 86 87 int val = (0xFF & (int) data[i]); 88 val <<= 8; 89 if ((i + 1) < data.length) { 90 val |= (0xFF & (int) data[i + 1]); 91 trip = true; 92 } 93 val <<= 8; 94 if ((i + 2) < data.length) { 95 val |= (0xFF & (int) data[i + 2]); 96 quad = true; 97 } 98 out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; 99 val >>= 6; 100 out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; 101 val >>= 6; 102 out[index + 1] = alphabet[val & 0x3F]; 103 val >>= 6; 104 out[index + 0] = alphabet[val & 0x3F]; 105 } 106 return out; 107 } 108 109 122 public static byte[] decode(char[] data) { 123 130 int tempLen = data.length; 131 for (int ix = 0; ix < data.length; ix++) { 132 if ((data[ix] > 255) || codes[ data[ix] ] < 0) { 133 --tempLen; } 135 } 136 141 int len = (tempLen / 4) * 3; 142 if ((tempLen % 4) == 3) { 143 len += 2; 144 } 145 if ((tempLen % 4) == 2) { 146 len += 1; 147 } 148 149 byte[] out = new byte[len]; 150 151 152 153 int shift = 0; int accum = 0; int index = 0; 156 157 for (int ix = 0; ix < data.length; ix++) { 159 int value = (data[ix] > 255) ? -1 : codes[ data[ix] ]; 160 161 if (value >= 0) { accum <<= 6; shift += 6; accum |= value; if (shift >= 8) { shift -= 8; out[index++] = (byte) ((accum >> shift) & 0xff); 169 } 170 } 171 } 178 179 if (index != out.length) { 181 throw new Error ("Miscalculated data length (wrote " + index + " instead of " + out.length + ")"); 182 } 183 184 return out; 185 } 186 187 188 189 } 190 | Popular Tags |