Exemplo n.º 1
0
  /**
   * Encodes binary data using the base64 algorithm, optionally chunking the output into 76
   * character blocks.
   *
   * @param binaryData Array containing binary data to encode.
   * @param isChunked if <code>true</code> this encoder will chunk the base64 output into 76
   *     character blocks
   * @return Base64-encoded data.
   * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than
   *     {@link Integer#MAX_VALUE}
   */
  public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
    if (binaryData == null || binaryData.length == 0) {
      return binaryData;
    }
    Base64 b64 = isChunked ? new Base64() : new Base64(0);

    long len = (binaryData.length * 4) / 3;
    long mod = len % 4;
    if (mod != 0) {
      len += 4 - mod;
    }
    if (isChunked) {
      len += (1 + (len / CHUNK_SIZE)) * CHUNK_SEPARATOR.length;
    }

    if (len > Integer.MAX_VALUE) {
      throw new IllegalArgumentException(
          "Input array too big, output array would be bigger than Integer.MAX_VALUE="
              + Integer.MAX_VALUE);
    }
    byte[] buf = new byte[(int) len];
    b64.setInitialBuffer(buf, 0, buf.length);
    b64.encode(binaryData, 0, binaryData.length);
    b64.encode(binaryData, 0, -1); // Notify encoder of EOF.

    // Encoder might have resized, even though it was unnecessary.
    if (b64.buf != buf) {
      b64.readResults(buf, 0, buf.length);
    }
    return buf;
  }
Exemplo n.º 2
0
  /**
   * Decodes Base64 data into octets
   *
   * @param base64Data Byte array containing Base64 data
   * @return Array containing decoded data.
   */
  public static byte[] decodeBase64(byte[] base64Data) {
    if (base64Data == null || base64Data.length == 0) {
      return base64Data;
    }
    Base64 b64 = new Base64();

    long len = (base64Data.length * 3) / 4;
    byte[] buf = new byte[(int) len];
    b64.setInitialBuffer(buf, 0, buf.length);
    b64.decode(base64Data, 0, base64Data.length);
    b64.decode(base64Data, 0, -1); // Notify decoder of EOF.

    // We have no idea what the line-length was, so we
    // cannot know how much of our array wasn't used.
    byte[] result = new byte[b64.pos];
    b64.readResults(result, 0, result.length);
    return result;
  }