Path: blob/master/src/java.prefs/share/classes/java/util/prefs/Base64.java
41159 views
/*1* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util.prefs;2627/**28* Static methods for translating Base64 encoded strings to byte arrays29* and vice-versa.30*31* @author Josh Bloch32* @see Preferences33* @since 1.434*/35class Base64 {36/**37* Translates the specified byte array into a Base64 string as per38* Preferences.put(byte[]).39*/40static String byteArrayToBase64(byte[] a) {41return byteArrayToBase64(a, false);42}4344/**45* Translates the specified byte array into an "alternate representation"46* Base64 string. This non-standard variant uses an alphabet that does47* not contain the uppercase alphabetic characters, which makes it48* suitable for use in situations where case-folding occurs.49*/50static String byteArrayToAltBase64(byte[] a) {51return byteArrayToBase64(a, true);52}5354private static String byteArrayToBase64(byte[] a, boolean alternate) {55int aLen = a.length;56int numFullGroups = aLen/3;57int numBytesInPartialGroup = aLen - 3*numFullGroups;58int resultLen = 4*((aLen + 2)/3);59StringBuilder result = new StringBuilder(resultLen);60char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64);6162// Translate all full groups from byte array elements to Base6463int inCursor = 0;64for (int i=0; i<numFullGroups; i++) {65int byte0 = a[inCursor++] & 0xff;66int byte1 = a[inCursor++] & 0xff;67int byte2 = a[inCursor++] & 0xff;68result.append(intToAlpha[byte0 >> 2]);69result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);70result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]);71result.append(intToAlpha[byte2 & 0x3f]);72}7374// Translate partial group if present75if (numBytesInPartialGroup != 0) {76int byte0 = a[inCursor++] & 0xff;77result.append(intToAlpha[byte0 >> 2]);78if (numBytesInPartialGroup == 1) {79result.append(intToAlpha[(byte0 << 4) & 0x3f]);80result.append("==");81} else {82// assert numBytesInPartialGroup == 2;83int byte1 = a[inCursor++] & 0xff;84result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);85result.append(intToAlpha[(byte1 << 2)&0x3f]);86result.append('=');87}88}89// assert inCursor == a.length;90// assert result.length() == resultLen;91return result.toString();92}9394/**95* This array is a lookup table that translates 6-bit positive integer96* index values into their "Base64 Alphabet" equivalents as specified97* in Table 1 of RFC 2045.98*/99private static final char intToBase64[] = {100'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',101'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',102'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',103'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',104'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'105};106107/**108* This array is a lookup table that translates 6-bit positive integer109* index values into their "Alternate Base64 Alphabet" equivalents.110* This is NOT the real Base64 Alphabet as per in Table 1 of RFC 2045.111* This alternate alphabet does not use the capital letters. It is112* designed for use in environments where "case folding" occurs.113*/114private static final char intToAltBase64[] = {115'!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':',116';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~',117'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',118'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',119'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '?'120};121122/**123* Translates the specified Base64 string (as per Preferences.get(byte[]))124* into a byte array.125*126* @throws IllegalArgumentException if {@code s} is not a valid Base64127* string.128*/129static byte[] base64ToByteArray(String s) {130return base64ToByteArray(s, false);131}132133/**134* Translates the specified "alternate representation" Base64 string135* into a byte array.136*137* @throws IllegalArgumentException or ArrayOutOfBoundsException138* if {@code s} is not a valid alternate representation139* Base64 string.140*/141static byte[] altBase64ToByteArray(String s) {142return base64ToByteArray(s, true);143}144145private static byte[] base64ToByteArray(String s, boolean alternate) {146byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt);147int sLen = s.length();148int numGroups = sLen/4;149if (4*numGroups != sLen)150throw new IllegalArgumentException(151"String length must be a multiple of four.");152int missingBytesInLastGroup = 0;153int numFullGroups = numGroups;154if (sLen != 0) {155if (s.charAt(sLen-1) == '=') {156missingBytesInLastGroup++;157numFullGroups--;158}159if (s.charAt(sLen-2) == '=')160missingBytesInLastGroup++;161}162byte[] result = new byte[3*numGroups - missingBytesInLastGroup];163164// Translate all full groups from base64 to byte array elements165int inCursor = 0, outCursor = 0;166for (int i=0; i<numFullGroups; i++) {167int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);168int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);169int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);170int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);171result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));172result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));173result[outCursor++] = (byte) ((ch2 << 6) | ch3);174}175176// Translate partial group, if present177if (missingBytesInLastGroup != 0) {178int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);179int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);180result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));181182if (missingBytesInLastGroup == 1) {183int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);184result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));185}186}187// assert inCursor == s.length()-missingBytesInLastGroup;188// assert outCursor == result.length;189return result;190}191192/**193* Translates the specified character, which is assumed to be in the194* "Base 64 Alphabet" into its equivalent 6-bit positive integer.195*196* @throws IllegalArgumentException or ArrayOutOfBoundsException if197* c is not in the Base64 Alphabet.198*/199private static int base64toInt(char c, byte[] alphaToInt) {200int result = alphaToInt[c];201if (result < 0)202throw new IllegalArgumentException("Illegal character " + c);203return result;204}205206/**207* This array is a lookup table that translates unicode characters208* drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)209* into their 6-bit positive integer equivalents. Characters that210* are not in the Base64 alphabet but fall within the bounds of the211* array are translated to -1.212*/213private static final byte base64ToInt[] = {214-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,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, 62, -1, -1, -1, 63, 52, 53, 54,21755, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,2185, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,21924, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,22035, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51221};222223/**224* This array is the analogue of base64ToInt, but for the nonstandard225* variant that avoids the use of uppercase alphabetic characters.226*/227private static final byte altBase64ToInt[] = {228-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,229-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,2302, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10, 11, -1 , 52, 53, 54, 55, 56, 57,23158, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1,232-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,233-1, -1, -1, 17, -1, 18, 19, 21, 20, 26, 27, 28, 29, 30, 31, 32, 33,23434, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,23551, 22, 23, 24, 25236};237238public static void main(String args[]) {239int numRuns = Integer.parseInt(args[0]);240int numBytes = Integer.parseInt(args[1]);241java.util.Random rnd = new java.util.Random();242for (int i=0; i<numRuns; i++) {243for (int j=0; j<numBytes; j++) {244byte[] arr = new byte[j];245for (int k=0; k<j; k++)246arr[k] = (byte)rnd.nextInt();247248String s = byteArrayToBase64(arr);249byte [] b = base64ToByteArray(s);250if (!java.util.Arrays.equals(arr, b))251System.out.println("Dismal failure!");252253s = byteArrayToAltBase64(arr);254b = altBase64ToByteArray(s);255if (!java.util.Arrays.equals(arr, b))256System.out.println("Alternate dismal failure!");257}258}259}260}261262263