Base64.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.codec.binary;

  18. import java.math.BigInteger;

  19. /**
  20.  * Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
  21.  *
  22.  * <p>
  23.  * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
  24.  * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
  25.  * </p>
  26.  * <p>
  27.  * The class can be parameterized in the following manner with various constructors:
  28.  * </p>
  29.  * <ul>
  30.  * <li>URL-safe mode: Default off.</li>
  31.  * <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of
  32.  * 4 in the encoded data.
  33.  * <li>Line separator: Default is CRLF ("\r\n")</li>
  34.  * </ul>
  35.  * <p>
  36.  * The URL-safe parameter is only applied to encode operations. Decoding seamlessly handles both modes.
  37.  * </p>
  38.  * <p>
  39.  * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only
  40.  * encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252,
  41.  * UTF-8, etc).
  42.  * </p>
  43.  * <p>
  44.  * This class is thread-safe.
  45.  * </p>
  46.  *
  47.  * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
  48.  * @since 1.0
  49.  * @version $Id: Base64.java 1789158 2017-03-28 15:04:58Z sebb $
  50.  */
  51. public class Base64 extends BaseNCodec {

  52.     /**
  53.      * BASE32 characters are 6 bits in length.
  54.      * They are formed by taking a block of 3 octets to form a 24-bit string,
  55.      * which is converted into 4 BASE64 characters.
  56.      */
  57.     private static final int BITS_PER_ENCODED_BYTE = 6;
  58.     private static final int BYTES_PER_UNENCODED_BLOCK = 3;
  59.     private static final int BYTES_PER_ENCODED_BLOCK = 4;

  60.     /**
  61.      * Chunk separator per RFC 2045 section 2.1.
  62.      *
  63.      * <p>
  64.      * N.B. The next major release may break compatibility and make this field private.
  65.      * </p>
  66.      *
  67.      * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
  68.      */
  69.     static final byte[] CHUNK_SEPARATOR = {'\r', '\n'};

  70.     /**
  71.      * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
  72.      * equivalents as specified in Table 1 of RFC 2045.
  73.      *
  74.      * Thanks to "commons" project in ws.apache.org for this code.
  75.      * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
  76.      */
  77.     private static final byte[] STANDARD_ENCODE_TABLE = {
  78.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  79.             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  80.             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  81.             'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  82.             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
  83.     };

  84.     /**
  85.      * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and /
  86.      * changed to - and _ to make the encoded Base64 results more URL-SAFE.
  87.      * This table is only used when the Base64's mode is set to URL-SAFE.
  88.      */
  89.     private static final byte[] URL_SAFE_ENCODE_TABLE = {
  90.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  91.             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  92.             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  93.             'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  94.             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
  95.     };

  96.     /**
  97.      * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified
  98.      * in Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
  99.      * alphabet but fall within the bounds of the array are translated to -1.
  100.      *
  101.      * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
  102.      * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
  103.      *
  104.      * Thanks to "commons" project in ws.apache.org for this code.
  105.      * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
  106.      */
  107.     private static final byte[] DECODE_TABLE = {
  108.         //   0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
  109.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
  110.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
  111.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, // 20-2f + - /
  112.             52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 30-3f 0-9
  113.             -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, // 40-4f A-O
  114.             15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, // 50-5f P-Z _
  115.             -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60-6f a-o
  116.             41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51                      // 70-7a p-z
  117.     };

  118.     /**
  119.      * Base64 uses 6-bit fields.
  120.      */
  121.     /** Mask used to extract 6 bits, used when encoding */
  122.     private static final int MASK_6BITS = 0x3f;

  123.     // The static final fields above are used for the original static byte[] methods on Base64.
  124.     // The private member fields below are used with the new streaming approach, which requires
  125.     // some state be preserved between calls of encode() and decode().

  126.     /**
  127.      * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able
  128.      * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch
  129.      * between the two modes.
  130.      */
  131.     private final byte[] encodeTable;

  132.     // Only one decode table currently; keep for consistency with Base32 code
  133.     private final byte[] decodeTable = DECODE_TABLE;

  134.     /**
  135.      * Line separator for encoding. Not used when decoding. Only used if lineLength &gt; 0.
  136.      */
  137.     private final byte[] lineSeparator;

  138.     /**
  139.      * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
  140.      * <code>decodeSize = 3 + lineSeparator.length;</code>
  141.      */
  142.     private final int decodeSize;

  143.     /**
  144.      * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
  145.      * <code>encodeSize = 4 + lineSeparator.length;</code>
  146.      */
  147.     private final int encodeSize;

  148.     /**
  149.      * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
  150.      * <p>
  151.      * When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE.
  152.      * </p>
  153.      *
  154.      * <p>
  155.      * When decoding all variants are supported.
  156.      * </p>
  157.      */
  158.     public Base64() {
  159.         this(0);
  160.     }

  161.     /**
  162.      * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.
  163.      * <p>
  164.      * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
  165.      * </p>
  166.      *
  167.      * <p>
  168.      * When decoding all variants are supported.
  169.      * </p>
  170.      *
  171.      * @param urlSafe
  172.      *            if <code>true</code>, URL-safe encoding is used. In most cases this should be set to
  173.      *            <code>false</code>.
  174.      * @since 1.4
  175.      */
  176.     public Base64(final boolean urlSafe) {
  177.         this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe);
  178.     }

  179.     /**
  180.      * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
  181.      * <p>
  182.      * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is
  183.      * STANDARD_ENCODE_TABLE.
  184.      * </p>
  185.      * <p>
  186.      * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
  187.      * </p>
  188.      * <p>
  189.      * When decoding all variants are supported.
  190.      * </p>
  191.      *
  192.      * @param lineLength
  193.      *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
  194.      *            4). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
  195.      *            decoding.
  196.      * @since 1.4
  197.      */
  198.     public Base64(final int lineLength) {
  199.         this(lineLength, CHUNK_SEPARATOR);
  200.     }

  201.     /**
  202.      * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
  203.      * <p>
  204.      * When encoding the line length and line separator are given in the constructor, and the encoding table is
  205.      * STANDARD_ENCODE_TABLE.
  206.      * </p>
  207.      * <p>
  208.      * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
  209.      * </p>
  210.      * <p>
  211.      * When decoding all variants are supported.
  212.      * </p>
  213.      *
  214.      * @param lineLength
  215.      *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
  216.      *            4). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
  217.      *            decoding.
  218.      * @param lineSeparator
  219.      *            Each line of encoded data will end with this sequence of bytes.
  220.      * @throws IllegalArgumentException
  221.      *             Thrown when the provided lineSeparator included some base64 characters.
  222.      * @since 1.4
  223.      */
  224.     public Base64(final int lineLength, final byte[] lineSeparator) {
  225.         this(lineLength, lineSeparator, false);
  226.     }

  227.     /**
  228.      * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
  229.      * <p>
  230.      * When encoding the line length and line separator are given in the constructor, and the encoding table is
  231.      * STANDARD_ENCODE_TABLE.
  232.      * </p>
  233.      * <p>
  234.      * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
  235.      * </p>
  236.      * <p>
  237.      * When decoding all variants are supported.
  238.      * </p>
  239.      *
  240.      * @param lineLength
  241.      *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
  242.      *            4). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
  243.      *            decoding.
  244.      * @param lineSeparator
  245.      *            Each line of encoded data will end with this sequence of bytes.
  246.      * @param urlSafe
  247.      *            Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
  248.      *            operations. Decoding seamlessly handles both modes.
  249.      *            <b>Note: no padding is added when using the URL-safe alphabet.</b>
  250.      * @throws IllegalArgumentException
  251.      *             The provided lineSeparator included some base64 characters. That's not going to work!
  252.      * @since 1.4
  253.      */
  254.     public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) {
  255.         super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK,
  256.                 lineLength,
  257.                 lineSeparator == null ? 0 : lineSeparator.length);
  258.         // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
  259.         // @see test case Base64Test.testConstructors()
  260.         if (lineSeparator != null) {
  261.             if (containsAlphabetOrPad(lineSeparator)) {
  262.                 final String sep = StringUtils.newStringUtf8(lineSeparator);
  263.                 throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
  264.             }
  265.             if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE
  266.                 this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
  267.                 this.lineSeparator = new byte[lineSeparator.length];
  268.                 System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
  269.             } else {
  270.                 this.encodeSize = BYTES_PER_ENCODED_BLOCK;
  271.                 this.lineSeparator = null;
  272.             }
  273.         } else {
  274.             this.encodeSize = BYTES_PER_ENCODED_BLOCK;
  275.             this.lineSeparator = null;
  276.         }
  277.         this.decodeSize = this.encodeSize - 1;
  278.         this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;
  279.     }

  280.     /**
  281.      * Returns our current encode mode. True if we're URL-SAFE, false otherwise.
  282.      *
  283.      * @return true if we're in URL-SAFE mode, false otherwise.
  284.      * @since 1.4
  285.      */
  286.     public boolean isUrlSafe() {
  287.         return this.encodeTable == URL_SAFE_ENCODE_TABLE;
  288.     }

  289.     /**
  290.      * <p>
  291.      * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
  292.      * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, to flush last
  293.      * remaining bytes (if not multiple of 3).
  294.      * </p>
  295.      * <p><b>Note: no padding is added when encoding using the URL-safe alphabet.</b></p>
  296.      * <p>
  297.      * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
  298.      * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
  299.      * </p>
  300.      *
  301.      * @param in
  302.      *            byte[] array of binary data to base64 encode.
  303.      * @param inPos
  304.      *            Position to start reading data from.
  305.      * @param inAvail
  306.      *            Amount of bytes available from input for encoding.
  307.      * @param context
  308.      *            the context to be used
  309.      */
  310.     @Override
  311.     void encode(final byte[] in, int inPos, final int inAvail, final Context context) {
  312.         if (context.eof) {
  313.             return;
  314.         }
  315.         // inAvail < 0 is how we're informed of EOF in the underlying data we're
  316.         // encoding.
  317.         if (inAvail < 0) {
  318.             context.eof = true;
  319.             if (0 == context.modulus && lineLength == 0) {
  320.                 return; // no leftovers to process and not using chunking
  321.             }
  322.             final byte[] buffer = ensureBufferSize(encodeSize, context);
  323.             final int savedPos = context.pos;
  324.             switch (context.modulus) { // 0-2
  325.                 case 0 : // nothing to do here
  326.                     break;
  327.                 case 1 : // 8 bits = 6 + 2
  328.                     // top 6 bits:
  329.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS];
  330.                     // remaining 2:
  331.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS];
  332.                     // URL-SAFE skips the padding to further reduce size.
  333.                     if (encodeTable == STANDARD_ENCODE_TABLE) {
  334.                         buffer[context.pos++] = pad;
  335.                         buffer[context.pos++] = pad;
  336.                     }
  337.                     break;

  338.                 case 2 : // 16 bits = 6 + 6 + 4
  339.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS];
  340.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS];
  341.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS];
  342.                     // URL-SAFE skips the padding to further reduce size.
  343.                     if (encodeTable == STANDARD_ENCODE_TABLE) {
  344.                         buffer[context.pos++] = pad;
  345.                     }
  346.                     break;
  347.                 default:
  348.                     throw new IllegalStateException("Impossible modulus "+context.modulus);
  349.             }
  350.             context.currentLinePos += context.pos - savedPos; // keep track of current line position
  351.             // if currentPos == 0 we are at the start of a line, so don't add CRLF
  352.             if (lineLength > 0 && context.currentLinePos > 0) {
  353.                 System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
  354.                 context.pos += lineSeparator.length;
  355.             }
  356.         } else {
  357.             for (int i = 0; i < inAvail; i++) {
  358.                 final byte[] buffer = ensureBufferSize(encodeSize, context);
  359.                 context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK;
  360.                 int b = in[inPos++];
  361.                 if (b < 0) {
  362.                     b += 256;
  363.                 }
  364.                 context.ibitWorkArea = (context.ibitWorkArea << 8) + b; //  BITS_PER_BYTE
  365.                 if (0 == context.modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract
  366.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS];
  367.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS];
  368.                     buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS];
  369.                     buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS];
  370.                     context.currentLinePos += BYTES_PER_ENCODED_BLOCK;
  371.                     if (lineLength > 0 && lineLength <= context.currentLinePos) {
  372.                         System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
  373.                         context.pos += lineSeparator.length;
  374.                         context.currentLinePos = 0;
  375.                     }
  376.                 }
  377.             }
  378.         }
  379.     }

  380.     /**
  381.      * <p>
  382.      * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
  383.      * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
  384.      * call is not necessary when decoding, but it doesn't hurt, either.
  385.      * </p>
  386.      * <p>
  387.      * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
  388.      * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
  389.      * garbage-out philosophy: it will not check the provided data for validity.
  390.      * </p>
  391.      * <p>
  392.      * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
  393.      * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
  394.      * </p>
  395.      *
  396.      * @param in
  397.      *            byte[] array of ascii data to base64 decode.
  398.      * @param inPos
  399.      *            Position to start reading data from.
  400.      * @param inAvail
  401.      *            Amount of bytes available from input for encoding.
  402.      * @param context
  403.      *            the context to be used
  404.      */
  405.     @Override
  406.     void decode(final byte[] in, int inPos, final int inAvail, final Context context) {
  407.         if (context.eof) {
  408.             return;
  409.         }
  410.         if (inAvail < 0) {
  411.             context.eof = true;
  412.         }
  413.         for (int i = 0; i < inAvail; i++) {
  414.             final byte[] buffer = ensureBufferSize(decodeSize, context);
  415.             final byte b = in[inPos++];
  416.             if (b == pad) {
  417.                 // We're done.
  418.                 context.eof = true;
  419.                 break;
  420.             }
  421.             if (b >= 0 && b < DECODE_TABLE.length) {
  422.                 final int result = DECODE_TABLE[b];
  423.                 if (result >= 0) {
  424.                     context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK;
  425.                     context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result;
  426.                     if (context.modulus == 0) {
  427.                         buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS);
  428.                         buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS);
  429.                         buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS);
  430.                     }
  431.                 }
  432.             }
  433.         }

  434.         // Two forms of EOF as far as base64 decoder is concerned: actual
  435.         // EOF (-1) and first time '=' character is encountered in stream.
  436.         // This approach makes the '=' padding characters completely optional.
  437.         if (context.eof && context.modulus != 0) {
  438.             final byte[] buffer = ensureBufferSize(decodeSize, context);

  439.             // We have some spare bits remaining
  440.             // Output all whole multiples of 8 bits and ignore the rest
  441.             switch (context.modulus) {
  442. //              case 0 : // impossible, as excluded above
  443.                 case 1 : // 6 bits - ignore entirely
  444.                     // TODO not currently tested; perhaps it is impossible?
  445.                     break;
  446.                 case 2 : // 12 bits = 8 + 4
  447.                     context.ibitWorkArea = context.ibitWorkArea >> 4; // dump the extra 4 bits
  448.                     buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS);
  449.                     break;
  450.                 case 3 : // 18 bits = 8 + 8 + 2
  451.                     context.ibitWorkArea = context.ibitWorkArea >> 2; // dump 2 bits
  452.                     buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS);
  453.                     buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS);
  454.                     break;
  455.                 default:
  456.                     throw new IllegalStateException("Impossible modulus "+context.modulus);
  457.             }
  458.         }
  459.     }

  460.     /**
  461.      * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
  462.      * method treats whitespace as valid.
  463.      *
  464.      * @param arrayOctet
  465.      *            byte array to test
  466.      * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
  467.      *         <code>false</code>, otherwise
  468.      * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
  469.      */
  470.     @Deprecated
  471.     public static boolean isArrayByteBase64(final byte[] arrayOctet) {
  472.         return isBase64(arrayOctet);
  473.     }

  474.     /**
  475.      * Returns whether or not the <code>octet</code> is in the base 64 alphabet.
  476.      *
  477.      * @param octet
  478.      *            The value to test
  479.      * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
  480.      * @since 1.4
  481.      */
  482.     public static boolean isBase64(final byte octet) {
  483.         return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1);
  484.     }

  485.     /**
  486.      * Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the
  487.      * method treats whitespace as valid.
  488.      *
  489.      * @param base64
  490.      *            String to test
  491.      * @return <code>true</code> if all characters in the String are valid characters in the Base64 alphabet or if
  492.      *         the String is empty; <code>false</code>, otherwise
  493.      *  @since 1.5
  494.      */
  495.     public static boolean isBase64(final String base64) {
  496.         return isBase64(StringUtils.getBytesUtf8(base64));
  497.     }

  498.     /**
  499.      * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
  500.      * method treats whitespace as valid.
  501.      *
  502.      * @param arrayOctet
  503.      *            byte array to test
  504.      * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
  505.      *         <code>false</code>, otherwise
  506.      * @since 1.5
  507.      */
  508.     public static boolean isBase64(final byte[] arrayOctet) {
  509.         for (int i = 0; i < arrayOctet.length; i++) {
  510.             if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) {
  511.                 return false;
  512.             }
  513.         }
  514.         return true;
  515.     }

  516.     /**
  517.      * Encodes binary data using the base64 algorithm but does not chunk the output.
  518.      *
  519.      * @param binaryData
  520.      *            binary data to encode
  521.      * @return byte[] containing Base64 characters in their UTF-8 representation.
  522.      */
  523.     public static byte[] encodeBase64(final byte[] binaryData) {
  524.         return encodeBase64(binaryData, false);
  525.     }

  526.     /**
  527.      * Encodes binary data using the base64 algorithm but does not chunk the output.
  528.      *
  529.      * NOTE:  We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to
  530.      * single-line non-chunking (commons-codec-1.5).
  531.      *
  532.      * @param binaryData
  533.      *            binary data to encode
  534.      * @return String containing Base64 characters.
  535.      * @since 1.4 (NOTE:  1.4 chunked the output, whereas 1.5 does not).
  536.      */
  537.     public static String encodeBase64String(final byte[] binaryData) {
  538.         return StringUtils.newStringUsAscii(encodeBase64(binaryData, false));
  539.     }

  540.     /**
  541.      * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
  542.      * url-safe variation emits - and _ instead of + and / characters.
  543.      * <b>Note: no padding is added.</b>
  544.      * @param binaryData
  545.      *            binary data to encode
  546.      * @return byte[] containing Base64 characters in their UTF-8 representation.
  547.      * @since 1.4
  548.      */
  549.     public static byte[] encodeBase64URLSafe(final byte[] binaryData) {
  550.         return encodeBase64(binaryData, false, true);
  551.     }

  552.     /**
  553.      * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
  554.      * url-safe variation emits - and _ instead of + and / characters.
  555.      * <b>Note: no padding is added.</b>
  556.      * @param binaryData
  557.      *            binary data to encode
  558.      * @return String containing Base64 characters
  559.      * @since 1.4
  560.      */
  561.     public static String encodeBase64URLSafeString(final byte[] binaryData) {
  562.         return StringUtils.newStringUsAscii(encodeBase64(binaryData, false, true));
  563.     }

  564.     /**
  565.      * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
  566.      *
  567.      * @param binaryData
  568.      *            binary data to encode
  569.      * @return Base64 characters chunked in 76 character blocks
  570.      */
  571.     public static byte[] encodeBase64Chunked(final byte[] binaryData) {
  572.         return encodeBase64(binaryData, true);
  573.     }

  574.     /**
  575.      * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
  576.      *
  577.      * @param binaryData
  578.      *            Array containing binary data to encode.
  579.      * @param isChunked
  580.      *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
  581.      * @return Base64-encoded data.
  582.      * @throws IllegalArgumentException
  583.      *             Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
  584.      */
  585.     public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) {
  586.         return encodeBase64(binaryData, isChunked, false);
  587.     }

  588.     /**
  589.      * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
  590.      *
  591.      * @param binaryData
  592.      *            Array containing binary data to encode.
  593.      * @param isChunked
  594.      *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
  595.      * @param urlSafe
  596.      *            if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
  597.      *            <b>Note: no padding is added when encoding using the URL-safe alphabet.</b>
  598.      * @return Base64-encoded data.
  599.      * @throws IllegalArgumentException
  600.      *             Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
  601.      * @since 1.4
  602.      */
  603.     public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) {
  604.         return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE);
  605.     }

  606.     /**
  607.      * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
  608.      *
  609.      * @param binaryData
  610.      *            Array containing binary data to encode.
  611.      * @param isChunked
  612.      *            if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
  613.      * @param urlSafe
  614.      *            if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
  615.      *            <b>Note: no padding is added when encoding using the URL-safe alphabet.</b>
  616.      * @param maxResultSize
  617.      *            The maximum result size to accept.
  618.      * @return Base64-encoded data.
  619.      * @throws IllegalArgumentException
  620.      *             Thrown when the input array needs an output array bigger than maxResultSize
  621.      * @since 1.4
  622.      */
  623.     public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked,
  624.                                       final boolean urlSafe, final int maxResultSize) {
  625.         if (binaryData == null || binaryData.length == 0) {
  626.             return binaryData;
  627.         }

  628.         // Create this so can use the super-class method
  629.         // Also ensures that the same roundings are performed by the ctor and the code
  630.         final Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
  631.         final long len = b64.getEncodedLength(binaryData);
  632.         if (len > maxResultSize) {
  633.             throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
  634.                 len +
  635.                 ") than the specified maximum size of " +
  636.                 maxResultSize);
  637.         }

  638.         return b64.encode(binaryData);
  639.     }

  640.     /**
  641.      * Decodes a Base64 String into octets.
  642.      * <p>
  643.      * <b>Note:</b> this method seamlessly handles data encoded in URL-safe or normal mode.
  644.      * </p>
  645.      *
  646.      * @param base64String
  647.      *            String containing Base64 data
  648.      * @return Array containing decoded data.
  649.      * @since 1.4
  650.      */
  651.     public static byte[] decodeBase64(final String base64String) {
  652.         return new Base64().decode(base64String);
  653.     }

  654.     /**
  655.      * Decodes Base64 data into octets.
  656.      * <p>
  657.      * <b>Note:</b> this method seamlessly handles data encoded in URL-safe or normal mode.
  658.      * </p>
  659.      *
  660.      * @param base64Data
  661.      *            Byte array containing Base64 data
  662.      * @return Array containing decoded data.
  663.      */
  664.     public static byte[] decodeBase64(final byte[] base64Data) {
  665.         return new Base64().decode(base64Data);
  666.     }

  667.     // Implementation of the Encoder Interface

  668.     // Implementation of integer encoding used for crypto
  669.     /**
  670.      * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.
  671.      *
  672.      * @param pArray
  673.      *            a byte array containing base64 character data
  674.      * @return A BigInteger
  675.      * @since 1.4
  676.      */
  677.     public static BigInteger decodeInteger(final byte[] pArray) {
  678.         return new BigInteger(1, decodeBase64(pArray));
  679.     }

  680.     /**
  681.      * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.
  682.      *
  683.      * @param bigInt
  684.      *            a BigInteger
  685.      * @return A byte array containing base64 character data
  686.      * @throws NullPointerException
  687.      *             if null is passed in
  688.      * @since 1.4
  689.      */
  690.     public static byte[] encodeInteger(final BigInteger bigInt) {
  691.         if (bigInt == null) {
  692.             throw new NullPointerException("encodeInteger called with null parameter");
  693.         }
  694.         return encodeBase64(toIntegerBytes(bigInt), false);
  695.     }

  696.     /**
  697.      * Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
  698.      *
  699.      * @param bigInt
  700.      *            <code>BigInteger</code> to be converted
  701.      * @return a byte array representation of the BigInteger parameter
  702.      */
  703.     static byte[] toIntegerBytes(final BigInteger bigInt) {
  704.         int bitlen = bigInt.bitLength();
  705.         // round bitlen
  706.         bitlen = ((bitlen + 7) >> 3) << 3;
  707.         final byte[] bigBytes = bigInt.toByteArray();

  708.         if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
  709.             return bigBytes;
  710.         }
  711.         // set up params for copying everything but sign bit
  712.         int startSrc = 0;
  713.         int len = bigBytes.length;

  714.         // if bigInt is exactly byte-aligned, just skip signbit in copy
  715.         if ((bigInt.bitLength() % 8) == 0) {
  716.             startSrc = 1;
  717.             len--;
  718.         }
  719.         final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
  720.         final byte[] resizedBytes = new byte[bitlen / 8];
  721.         System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
  722.         return resizedBytes;
  723.     }

  724.     /**
  725.      * Returns whether or not the <code>octet</code> is in the Base64 alphabet.
  726.      *
  727.      * @param octet
  728.      *            The value to test
  729.      * @return <code>true</code> if the value is defined in the the Base64 alphabet <code>false</code> otherwise.
  730.      */
  731.     @Override
  732.     protected boolean isInAlphabet(final byte octet) {
  733.         return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
  734.     }

  735. }