// $Id: Base64.java 230957 2005-08-09 02:35:29Z hans $ // // (C) Copyright 2005 VeriSign, Inc. All Rights Reserved. // // VeriSign, Inc. shall have no responsibility, financial or // otherwise, for any consequences arising out of the use of // this material. The program material is provided on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. The user is responsible for determining // any necessary third party rights or authorizations that may // be required for the use of the materials. Users are advised // that they may need authorizations under certain patents from // Microsoft and IBM, or others. Please see notice.txt file. // VeriSign disclaims any obligation to notify the user of any // such third party rights. // import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; /** * Provides conversion methods between Base64 strings and byte arrays. */ public class Base64 { private static final String base64String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/="; private static final char[] base64Digits = base64String.toCharArray(); private static final byte[] base64Values = getBase64Values(); private static final int MAX_LINE_LENGTH = 72; private static byte[] getBase64Values() { byte[] result = new byte[125]; Arrays.fill(result, (byte)-1); for (byte i=0; i=0) { // only look at valid digits if (value>=64) { break; } // terminate on '=' buffer<<=6; buffer|=value; goodBits += 6; if (goodBits>=8) { baos.write( (buffer >> (goodBits-8)) & 0xff); goodBits -= 8; } } } } byte[] result = baos.toByteArray(); releaseBAOS(baos); return result; } /** * Converts a byte array to a Base64-encoded string. * *

Lines will contain a maximum of 72 characters of data and "\n" * will be used as the line separator.

* * @param data is the byte array. * * @return the Base64-encoded string. */ public static String encode(byte[] data) { return encode(data, MAX_LINE_LENGTH, "\n"); } private static String encode(byte[] data, int maxLineLength, String lineSeparator) { if (lineSeparator == null) { lineSeparator = ""; } StringBuffer result = new StringBuffer(); int buffer = 0; int goodBits = 0; int lineLen = 0; for (int i=0; i=6) { int value = (buffer >> (goodBits-6)) & 0x3f; result.append(base64Digits[value]); goodBits -= 6; lineLen++; if (lineLen >= maxLineLength) { lineLen = 0; result.append(lineSeparator); } } } if (goodBits>0) { int value = (buffer<<(6-goodBits)) & 0x3f; result.append(base64Digits[value]); lineLen++; } switch (lineLen % 4) { case 0: break; case 1: result.append("==="); break; case 2: result.append("=="); break; case 3: result.append("="); break; } return result.toString(); } }