1 /*
2  * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.util.prefs;
27 
28 /**
29  * Static methods for translating Base64 encoded strings to byte arrays
30  * and vice-versa.
31  *
32  * @author  Josh Bloch
33  * @see     Preferences
34  * @since   1.4
35  */
36 class Base64 {
37     /**
38      * Translates the specified byte array into a Base64 string as per
39      * Preferences.put(byte[]).
40      */
byteArrayToBase64(byte[] a)41     static String byteArrayToBase64(byte[] a) {
42         return byteArrayToBase64(a, false);
43     }
44 
45     /**
46      * Translates the specified byte array into an "alternate representation"
47      * Base64 string.  This non-standard variant uses an alphabet that does
48      * not contain the uppercase alphabetic characters, which makes it
49      * suitable for use in situations where case-folding occurs.
50      */
byteArrayToAltBase64(byte[] a)51     static String byteArrayToAltBase64(byte[] a) {
52         return byteArrayToBase64(a, true);
53     }
54 
byteArrayToBase64(byte[] a, boolean alternate)55     private static String byteArrayToBase64(byte[] a, boolean alternate) {
56         int aLen = a.length;
57         int numFullGroups = aLen/3;
58         int numBytesInPartialGroup = aLen - 3*numFullGroups;
59         int resultLen = 4*((aLen + 2)/3);
60         StringBuffer result = new StringBuffer(resultLen);
61         char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64);
62 
63         // Translate all full groups from byte array elements to Base64
64         int inCursor = 0;
65         for (int i=0; i<numFullGroups; i++) {
66             int byte0 = a[inCursor++] & 0xff;
67             int byte1 = a[inCursor++] & 0xff;
68             int byte2 = a[inCursor++] & 0xff;
69             result.append(intToAlpha[byte0 >> 2]);
70             result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
71             result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]);
72             result.append(intToAlpha[byte2 & 0x3f]);
73         }
74 
75         // Translate partial group if present
76         if (numBytesInPartialGroup != 0) {
77             int byte0 = a[inCursor++] & 0xff;
78             result.append(intToAlpha[byte0 >> 2]);
79             if (numBytesInPartialGroup == 1) {
80                 result.append(intToAlpha[(byte0 << 4) & 0x3f]);
81                 result.append("==");
82             } else {
83                 // assert numBytesInPartialGroup == 2;
84                 int byte1 = a[inCursor++] & 0xff;
85                 result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
86                 result.append(intToAlpha[(byte1 << 2)&0x3f]);
87                 result.append('=');
88             }
89         }
90         // assert inCursor == a.length;
91         // assert result.length() == resultLen;
92         return result.toString();
93     }
94 
95     /**
96      * This array is a lookup table that translates 6-bit positive integer
97      * index values into their "Base64 Alphabet" equivalents as specified
98      * in Table 1 of RFC 2045.
99      */
100     private static final char intToBase64[] = {
101         'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
102         'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
103         'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
104         'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
105         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
106     };
107 
108     /**
109      * This array is a lookup table that translates 6-bit positive integer
110      * index values into their "Alternate Base64 Alphabet" equivalents.
111      * This is NOT the real Base64 Alphabet as per in Table 1 of RFC 2045.
112      * This alternate alphabet does not use the capital letters.  It is
113      * designed for use in environments where "case folding" occurs.
114      */
115     private static final char intToAltBase64[] = {
116         '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':',
117         ';', '<', '>', '@', '[', ']', '^',  '`', '_', '{', '|', '}', '~',
118         'a', 'b', 'c', 'd', 'e', 'f', 'g',  'h', 'i', 'j', 'k', 'l', 'm',
119         'n', 'o', 'p', 'q', 'r', 's', 't',  'u', 'v', 'w', 'x', 'y', 'z',
120         '0', '1', '2', '3', '4', '5', '6',  '7', '8', '9', '+', '?'
121     };
122 
123     /**
124      * Translates the specified Base64 string (as per Preferences.get(byte[]))
125      * into a byte array.
126      *
127      * @throw IllegalArgumentException if <tt>s</tt> is not a valid Base64
128      *        string.
129      */
base64ToByteArray(String s)130     static byte[] base64ToByteArray(String s) {
131         return base64ToByteArray(s, false);
132     }
133 
134     /**
135      * Translates the specified "alternate representation" Base64 string
136      * into a byte array.
137      *
138      * @throw IllegalArgumentException or ArrayOutOfBoundsException
139      *        if <tt>s</tt> is not a valid alternate representation
140      *        Base64 string.
141      */
altBase64ToByteArray(String s)142     static byte[] altBase64ToByteArray(String s) {
143         return base64ToByteArray(s, true);
144     }
145 
base64ToByteArray(String s, boolean alternate)146     private static byte[] base64ToByteArray(String s, boolean alternate) {
147         byte[] alphaToInt = (alternate ?  altBase64ToInt : base64ToInt);
148         int sLen = s.length();
149         int numGroups = sLen/4;
150         if (4*numGroups != sLen)
151             throw new IllegalArgumentException(
152                 "String length must be a multiple of four.");
153         int missingBytesInLastGroup = 0;
154         int numFullGroups = numGroups;
155         if (sLen != 0) {
156             if (s.charAt(sLen-1) == '=') {
157                 missingBytesInLastGroup++;
158                 numFullGroups--;
159             }
160             if (s.charAt(sLen-2) == '=')
161                 missingBytesInLastGroup++;
162         }
163         byte[] result = new byte[3*numGroups - missingBytesInLastGroup];
164 
165         // Translate all full groups from base64 to byte array elements
166         int inCursor = 0, outCursor = 0;
167         for (int i=0; i<numFullGroups; i++) {
168             int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
169             int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
170             int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
171             int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
172             result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
173             result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
174             result[outCursor++] = (byte) ((ch2 << 6) | ch3);
175         }
176 
177         // Translate partial group, if present
178         if (missingBytesInLastGroup != 0) {
179             int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
180             int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
181             result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
182 
183             if (missingBytesInLastGroup == 1) {
184                 int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
185                 result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
186             }
187         }
188         // assert inCursor == s.length()-missingBytesInLastGroup;
189         // assert outCursor == result.length;
190         return result;
191     }
192 
193     /**
194      * Translates the specified character, which is assumed to be in the
195      * "Base 64 Alphabet" into its equivalent 6-bit positive integer.
196      *
197      * @throw IllegalArgumentException or ArrayOutOfBoundsException if
198      *        c is not in the Base64 Alphabet.
199      */
base64toInt(char c, byte[] alphaToInt)200     private static int base64toInt(char c, byte[] alphaToInt) {
201         int result = alphaToInt[c];
202         if (result < 0)
203             throw new IllegalArgumentException("Illegal character " + c);
204         return result;
205     }
206 
207     /**
208      * This array is a lookup table that translates unicode characters
209      * drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
210      * into their 6-bit positive integer equivalents.  Characters that
211      * are not in the Base64 alphabet but fall within the bounds of the
212      * array are translated to -1.
213      */
214     private static final byte base64ToInt[] = {
215         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
216         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
217         -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
218         55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
219         5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
220         24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
221         35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
222     };
223 
224     /**
225      * This array is the analogue of base64ToInt, but for the nonstandard
226      * variant that avoids the use of uppercase alphabetic characters.
227      */
228     private static final byte altBase64ToInt[] = {
229         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
230         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
231         2, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10, 11, -1 , 52, 53, 54, 55, 56, 57,
232         58, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1,
233         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
234         -1, -1, -1, 17, -1, 18, 19, 21, 20, 26, 27, 28, 29, 30, 31, 32, 33,
235         34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
236         51, 22, 23, 24, 25
237     };
238 
main(String args[])239     public static void main(String args[]) {
240         int numRuns  = Integer.parseInt(args[0]);
241         int numBytes = Integer.parseInt(args[1]);
242         java.util.Random rnd = new java.util.Random();
243         for (int i=0; i<numRuns; i++) {
244             for (int j=0; j<numBytes; j++) {
245                 byte[] arr = new byte[j];
246                 for (int k=0; k<j; k++)
247                     arr[k] = (byte)rnd.nextInt();
248 
249                 String s = byteArrayToBase64(arr);
250                 byte [] b = base64ToByteArray(s);
251                 if (!java.util.Arrays.equals(arr, b))
252                     System.out.println("Dismal failure!");
253 
254                 s = byteArrayToAltBase64(arr);
255                 b = altBase64ToByteArray(s);
256                 if (!java.util.Arrays.equals(arr, b))
257                     System.out.println("Alternate dismal failure!");
258             }
259         }
260     }
261 }
262