001 /*
002 * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 package java.util.prefs;
027
028 /**
029 * Static methods for translating Base64 encoded strings to byte arrays
030 * and vice-versa.
031 *
032 * @author Josh Bloch
033 * @version 1.13, 05/05/07
034 * @see Preferences
035 * @since 1.4
036 */
037 class Base64 {
038 /**
039 * Translates the specified byte array into a Base64 string as per
040 * Preferences.put(byte[]).
041 */
042 static String byteArrayToBase64(byte[] a) {
043 return byteArrayToBase64(a, false);
044 }
045
046 /**
047 * Translates the specified byte array into an "alternate representation"
048 * Base64 string. This non-standard variant uses an alphabet that does
049 * not contain the uppercase alphabetic characters, which makes it
050 * suitable for use in situations where case-folding occurs.
051 */
052 static String byteArrayToAltBase64(byte[] a) {
053 return byteArrayToBase64(a, true);
054 }
055
056 private static String byteArrayToBase64(byte[] a, boolean alternate) {
057 int aLen = a.length;
058 int numFullGroups = aLen / 3;
059 int numBytesInPartialGroup = aLen - 3 * numFullGroups;
060 int resultLen = 4 * ((aLen + 2) / 3);
061 StringBuffer result = new StringBuffer(resultLen);
062 char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64);
063
064 // Translate all full groups from byte array elements to Base64
065 int inCursor = 0;
066 for (int i = 0; i < numFullGroups; i++) {
067 int byte0 = a[inCursor++] & 0xff;
068 int byte1 = a[inCursor++] & 0xff;
069 int byte2 = a[inCursor++] & 0xff;
070 result.append(intToAlpha[byte0 >> 2]);
071 result
072 .append(intToAlpha[(byte0 << 4) & 0x3f
073 | (byte1 >> 4)]);
074 result
075 .append(intToAlpha[(byte1 << 2) & 0x3f
076 | (byte2 >> 6)]);
077 result.append(intToAlpha[byte2 & 0x3f]);
078 }
079
080 // Translate partial group if present
081 if (numBytesInPartialGroup != 0) {
082 int byte0 = a[inCursor++] & 0xff;
083 result.append(intToAlpha[byte0 >> 2]);
084 if (numBytesInPartialGroup == 1) {
085 result.append(intToAlpha[(byte0 << 4) & 0x3f]);
086 result.append("==");
087 } else {
088 // assert numBytesInPartialGroup == 2;
089 int byte1 = a[inCursor++] & 0xff;
090 result.append(intToAlpha[(byte0 << 4) & 0x3f
091 | (byte1 >> 4)]);
092 result.append(intToAlpha[(byte1 << 2) & 0x3f]);
093 result.append('=');
094 }
095 }
096 // assert inCursor == a.length;
097 // assert result.length() == resultLen;
098 return result.toString();
099 }
100
101 /**
102 * This array is a lookup table that translates 6-bit positive integer
103 * index values into their "Base64 Alphabet" equivalents as specified
104 * in Table 1 of RFC 2045.
105 */
106 private static final char intToBase64[] = { 'A', 'B', 'C', 'D',
107 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
108 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
109 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
110 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
111 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
112
113 /**
114 * This array is a lookup table that translates 6-bit positive integer
115 * index values into their "Alternate Base64 Alphabet" equivalents.
116 * This is NOT the real Base64 Alphabet as per in Table 1 of RFC 2045.
117 * This alternate alphabet does not use the capital letters. It is
118 * designed for use in environments where "case folding" occurs.
119 */
120 private static final char intToAltBase64[] = { '!', '"', '#', '$',
121 '%', '&', '\'', '(', ')', ',', '-', '.', ':', ';', '<',
122 '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~', 'a',
123 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
124 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
125 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+',
126 '?' };
127
128 /**
129 * Translates the specified Base64 string (as per Preferences.get(byte[]))
130 * into a byte array.
131 *
132 * @throw IllegalArgumentException if <tt>s</tt> is not a valid Base64
133 * string.
134 */
135 static byte[] base64ToByteArray(String s) {
136 return base64ToByteArray(s, false);
137 }
138
139 /**
140 * Translates the specified "alternate representation" Base64 string
141 * into a byte array.
142 *
143 * @throw IllegalArgumentException or ArrayOutOfBoundsException
144 * if <tt>s</tt> is not a valid alternate representation
145 * Base64 string.
146 */
147 static byte[] altBase64ToByteArray(String s) {
148 return base64ToByteArray(s, true);
149 }
150
151 private static byte[] base64ToByteArray(String s, boolean alternate) {
152 byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt);
153 int sLen = s.length();
154 int numGroups = sLen / 4;
155 if (4 * numGroups != sLen)
156 throw new IllegalArgumentException(
157 "String length must be a multiple of four.");
158 int missingBytesInLastGroup = 0;
159 int numFullGroups = numGroups;
160 if (sLen != 0) {
161 if (s.charAt(sLen - 1) == '=') {
162 missingBytesInLastGroup++;
163 numFullGroups--;
164 }
165 if (s.charAt(sLen - 2) == '=')
166 missingBytesInLastGroup++;
167 }
168 byte[] result = new byte[3 * numGroups
169 - missingBytesInLastGroup];
170
171 // Translate all full groups from base64 to byte array elements
172 int inCursor = 0, outCursor = 0;
173 for (int i = 0; i < numFullGroups; i++) {
174 int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
175 int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
176 int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
177 int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
178 result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
179 result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
180 result[outCursor++] = (byte) ((ch2 << 6) | ch3);
181 }
182
183 // Translate partial group, if present
184 if (missingBytesInLastGroup != 0) {
185 int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
186 int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
187 result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
188
189 if (missingBytesInLastGroup == 1) {
190 int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
191 result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
192 }
193 }
194 // assert inCursor == s.length()-missingBytesInLastGroup;
195 // assert outCursor == result.length;
196 return result;
197 }
198
199 /**
200 * Translates the specified character, which is assumed to be in the
201 * "Base 64 Alphabet" into its equivalent 6-bit positive integer.
202 *
203 * @throw IllegalArgumentException or ArrayOutOfBoundsException if
204 * c is not in the Base64 Alphabet.
205 */
206 private static int base64toInt(char c, byte[] alphaToInt) {
207 int result = alphaToInt[c];
208 if (result < 0)
209 throw new IllegalArgumentException("Illegal character " + c);
210 return result;
211 }
212
213 /**
214 * This array is a lookup table that translates unicode characters
215 * drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
216 * into their 6-bit positive integer equivalents. Characters that
217 * are not in the Base64 alphabet but fall within the bounds of the
218 * array are translated to -1.
219 */
220 private static final byte base64ToInt[] = { -1, -1, -1, -1, -1, -1,
221 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
222 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
223 -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
224 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0,
225 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
226 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,
227 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
228 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
229
230 /**
231 * This array is the analogue of base64ToInt, but for the nonstandard
232 * variant that avoids the use of uppercase alphabetic characters.
233 */
234 private static final byte altBase64ToInt[] = { -1, -1, -1, -1, -1,
235 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
236 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
237 2, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10, 11, -1, 52, 53, 54, 55,
238 56, 57, 58, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1,
239 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
240 -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, 18, 19, 21, 20,
241 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
242 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 22, 23, 24, 25 };
243
244 public static void main(String args[]) {
245 int numRuns = Integer.parseInt(args[0]);
246 int numBytes = Integer.parseInt(args[1]);
247 java.util.Random rnd = new java.util.Random();
248 for (int i = 0; i < numRuns; i++) {
249 for (int j = 0; j < numBytes; j++) {
250 byte[] arr = new byte[j];
251 for (int k = 0; k < j; k++)
252 arr[k] = (byte) rnd.nextInt();
253
254 String s = byteArrayToBase64(arr);
255 byte[] b = base64ToByteArray(s);
256 if (!java.util.Arrays.equals(arr, b))
257 System.out.println("Dismal failure!");
258
259 s = byteArrayToAltBase64(arr);
260 b = altBase64ToByteArray(s);
261 if (!java.util.Arrays.equals(arr, b))
262 System.out.println("Alternate dismal failure!");
263 }
264 }
265 }
266 }
|