| 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 | |
| 18 | /* |
| 19 | Copyright (c) 2012-2023, Michael Angstadt |
| 20 | All rights reserved. |
| 21 | |
| 22 | Redistribution and use in source and binary forms, with or without |
| 23 | modification, are permitted provided that the following conditions are met: |
| 24 | |
| 25 | 1. Redistributions of source code must retain the above copyright notice, this |
| 26 | list of conditions and the following disclaimer. |
| 27 | 2. Redistributions in binary form must reproduce the above copyright notice, |
| 28 | this list of conditions and the following disclaimer in the documentation |
| 29 | and/or other materials provided with the distribution. |
| 30 | |
| 31 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 32 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 33 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 34 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR |
| 35 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
| 36 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
| 37 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
| 38 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 39 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 40 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 41 | |
| 42 | The views and conclusions contained in the software and documentation are those |
| 43 | of the authors and should not be interpreted as representing official policies, |
| 44 | either expressed or implied, of the FreeBSD Project. |
| 45 | */ |
| 46 | |
| 47 | package ezvcard.util.org.apache.commons.codec.binary; |
| 48 | |
| 49 | import java.math.BigInteger; |
| 50 | |
| 51 | /** |
| 52 | * Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>. |
| 53 | * |
| 54 | * <p> |
| 55 | * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose |
| 56 | * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein. |
| 57 | * </p> |
| 58 | * <p> |
| 59 | * The class can be parameterized in the following manner with various constructors: |
| 60 | * </p> |
| 61 | * <ul> |
| 62 | * <li>URL-safe mode: Default off.</li> |
| 63 | * <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of |
| 64 | * 4 in the encoded data. |
| 65 | * <li>Line separator: Default is CRLF ("\r\n")</li> |
| 66 | * </ul> |
| 67 | * <p> |
| 68 | * The URL-safe parameter is only applied to encode operations. Decoding seamlessly handles both modes. |
| 69 | * </p> |
| 70 | * <p> |
| 71 | * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only |
| 72 | * encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, |
| 73 | * UTF-8, etc). |
| 74 | * </p> |
| 75 | * <p> |
| 76 | * This class is thread-safe. |
| 77 | * </p> |
| 78 | * <p> |
| 79 | * <b><i>ez-vcard integration note</i></b>: Minor modifications were made to this class so that it could be |
| 80 | * incorporated into the ez-vcard code base. Defining the Apache Commons Codec library as a project dependency causes |
| 81 | * an issue with Android devices, which is why parts of its source code have been directly incorporated into the |
| 82 | * ez-vcard code base. |
| 83 | * </p> |
| 84 | * |
| 85 | * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> |
| 86 | * @since 1.0 |
| 87 | * @version $Id: Base64.java 1635986 2014-11-01 16:27:52Z tn $ |
| 88 | */ |
| 89 | public class Base64 extends BaseNCodec { |
| 90 | |
| 91 | /** |
| 92 | * BASE32 characters are 6 bits in length. |
| 93 | * They are formed by taking a block of 3 octets to form a 24-bit string, |
| 94 | * which is converted into 4 BASE64 characters. |
| 95 | */ |
| 96 | private static final int BITS_PER_ENCODED_BYTE = 6; |
| 97 | private static final int BYTES_PER_UNENCODED_BLOCK = 3; |
| 98 | private static final int BYTES_PER_ENCODED_BLOCK = 4; |
| 99 | |
| 100 | /** |
| 101 | * Chunk separator per RFC 2045 section 2.1. |
| 102 | * |
| 103 | * <p> |
| 104 | * N.B. The next major release may break compatibility and make this field private. |
| 105 | * </p> |
| 106 | * |
| 107 | * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a> |
| 108 | */ |
| 109 | static final byte[] CHUNK_SEPARATOR = {'\r', '\n'}; |
| 110 | |
| 111 | /** |
| 112 | * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" |
| 113 | * equivalents as specified in Table 1 of RFC 2045. |
| 114 | * |
| 115 | * Thanks to "commons" project in ws.apache.org for this code. |
| 116 | * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ |
| 117 | */ |
| 118 | private static final byte[] STANDARD_ENCODE_TABLE = { |
| 119 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', |
| 120 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', |
| 121 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', |
| 122 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', |
| 123 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' |
| 124 | }; |
| 125 | |
| 126 | /** |
| 127 | * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / |
| 128 | * changed to - and _ to make the encoded Base64 results more URL-SAFE. |
| 129 | * This table is only used when the Base64's mode is set to URL-SAFE. |
| 130 | */ |
| 131 | private static final byte[] URL_SAFE_ENCODE_TABLE = { |
| 132 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', |
| 133 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', |
| 134 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', |
| 135 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', |
| 136 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' |
| 137 | }; |
| 138 | |
| 139 | /** |
| 140 | * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified |
| 141 | * in Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64 |
| 142 | * alphabet but fall within the bounds of the array are translated to -1. |
| 143 | * |
| 144 | * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both |
| 145 | * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit). |
| 146 | * |
| 147 | * Thanks to "commons" project in ws.apache.org for this code. |
| 148 | * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ |
| 149 | */ |
| 150 | private static final byte[] DECODE_TABLE = { |
| 151 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
| 152 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
| 153 | -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54, |
| 154 | 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, |
| 155 | 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, |
| 156 | 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, |
| 157 | 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 |
| 158 | }; |
| 159 | |
| 160 | /** |
| 161 | * Base64 uses 6-bit fields. |
| 162 | */ |
| 163 | /** Mask used to extract 6 bits, used when encoding */ |
| 164 | private static final int MASK_6BITS = 0x3f; |
| 165 | |
| 166 | // The static final fields above are used for the original static byte[] methods on Base64. |
| 167 | // The private member fields below are used with the new streaming approach, which requires |
| 168 | // some state be preserved between calls of encode() and decode(). |
| 169 | |
| 170 | /** |
| 171 | * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able |
| 172 | * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch |
| 173 | * between the two modes. |
| 174 | */ |
| 175 | private final byte[] encodeTable; |
| 176 | |
| 177 | // Only one decode table currently; keep for consistency with Base32 code |
| 178 | private final byte[] decodeTable = DECODE_TABLE; |
| 179 | |
| 180 | /** |
| 181 | * Line separator for encoding. Not used when decoding. Only used if lineLength > 0. |
| 182 | */ |
| 183 | private final byte[] lineSeparator; |
| 184 | |
| 185 | /** |
| 186 | * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. |
| 187 | * <code>decodeSize = 3 + lineSeparator.length;</code> |
| 188 | */ |
| 189 | private final int decodeSize; |
| 190 | |
| 191 | /** |
| 192 | * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. |
| 193 | * <code>encodeSize = 4 + lineSeparator.length;</code> |
| 194 | */ |
| 195 | private final int encodeSize; |
| 196 | |
| 197 | /** |
| 198 | * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. |
| 199 | * <p> |
| 200 | * When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE. |
| 201 | * </p> |
| 202 | * |
| 203 | * <p> |
| 204 | * When decoding all variants are supported. |
| 205 | * </p> |
| 206 | */ |
| 207 | public Base64() { |
| 208 | this(0); |
| 209 | } |
| 210 | |
| 211 | /** |
| 212 | * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode. |
| 213 | * <p> |
| 214 | * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE. |
| 215 | * </p> |
| 216 | * |
| 217 | * <p> |
| 218 | * When decoding all variants are supported. |
| 219 | * </p> |
| 220 | * |
| 221 | * @param urlSafe |
| 222 | * if <code>true</code>, URL-safe encoding is used. In most cases this should be set to |
| 223 | * <code>false</code>. |
| 224 | * @since 1.4 |
| 225 | */ |
| 226 | public Base64(final boolean urlSafe) { |
| 227 | this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe); |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. |
| 232 | * <p> |
| 233 | * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is |
| 234 | * STANDARD_ENCODE_TABLE. |
| 235 | * </p> |
| 236 | * <p> |
| 237 | * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. |
| 238 | * </p> |
| 239 | * <p> |
| 240 | * When decoding all variants are supported. |
| 241 | * </p> |
| 242 | * |
| 243 | * @param lineLength |
| 244 | * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of |
| 245 | * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when |
| 246 | * decoding. |
| 247 | * @since 1.4 |
| 248 | */ |
| 249 | public Base64(final int lineLength) { |
| 250 | this(lineLength, CHUNK_SEPARATOR); |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. |
| 255 | * <p> |
| 256 | * When encoding the line length and line separator are given in the constructor, and the encoding table is |
| 257 | * STANDARD_ENCODE_TABLE. |
| 258 | * </p> |
| 259 | * <p> |
| 260 | * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. |
| 261 | * </p> |
| 262 | * <p> |
| 263 | * When decoding all variants are supported. |
| 264 | * </p> |
| 265 | * |
| 266 | * @param lineLength |
| 267 | * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of |
| 268 | * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when |
| 269 | * decoding. |
| 270 | * @param lineSeparator |
| 271 | * Each line of encoded data will end with this sequence of bytes. |
| 272 | * @throws IllegalArgumentException |
| 273 | * Thrown when the provided lineSeparator included some base64 characters. |
| 274 | * @since 1.4 |
| 275 | */ |
| 276 | public Base64(final int lineLength, final byte[] lineSeparator) { |
| 277 | this(lineLength, lineSeparator, false); |
| 278 | } |
| 279 | |
| 280 | /** |
| 281 | * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. |
| 282 | * <p> |
| 283 | * When encoding the line length and line separator are given in the constructor, and the encoding table is |
| 284 | * STANDARD_ENCODE_TABLE. |
| 285 | * </p> |
| 286 | * <p> |
| 287 | * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. |
| 288 | * </p> |
| 289 | * <p> |
| 290 | * When decoding all variants are supported. |
| 291 | * </p> |
| 292 | * |
| 293 | * @param lineLength |
| 294 | * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of |
| 295 | * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when |
| 296 | * decoding. |
| 297 | * @param lineSeparator |
| 298 | * Each line of encoded data will end with this sequence of bytes. |
| 299 | * @param urlSafe |
| 300 | * Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode |
| 301 | * operations. Decoding seamlessly handles both modes. |
| 302 | * <b>Note: no padding is added when using the URL-safe alphabet.</b> |
| 303 | * @throws IllegalArgumentException |
| 304 | * The provided lineSeparator included some base64 characters. That's not going to work! |
| 305 | * @since 1.4 |
| 306 | */ |
| 307 | public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) { |
| 308 | super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, |
| 309 | lineLength, |
| 310 | lineSeparator == null ? 0 : lineSeparator.length); |
| 311 | // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0 |
| 312 | // @see test case Base64Test.testConstructors() |
| 313 | if (lineSeparator != null) { |
| 314 | if (containsAlphabetOrPad(lineSeparator)) { |
| 315 | final String sep = newStringUtf8(lineSeparator); |
| 316 | throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]"); |
| 317 | } |
| 318 | if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE |
| 319 | this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length; |
| 320 | this.lineSeparator = new byte[lineSeparator.length]; |
| 321 | System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length); |
| 322 | } else { |
| 323 | this.encodeSize = BYTES_PER_ENCODED_BLOCK; |
| 324 | this.lineSeparator = null; |
| 325 | } |
| 326 | } else { |
| 327 | this.encodeSize = BYTES_PER_ENCODED_BLOCK; |
| 328 | this.lineSeparator = null; |
| 329 | } |
| 330 | this.decodeSize = this.encodeSize - 1; |
| 331 | this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE; |
| 332 | } |
| 333 | |
| 334 | /** |
| 335 | * Returns our current encode mode. True if we're URL-SAFE, false otherwise. |
| 336 | * |
| 337 | * @return true if we're in URL-SAFE mode, false otherwise. |
| 338 | * @since 1.4 |
| 339 | */ |
| 340 | public boolean isUrlSafe() { |
| 341 | return this.encodeTable == URL_SAFE_ENCODE_TABLE; |
| 342 | } |
| 343 | |
| 344 | /** |
| 345 | * <p> |
| 346 | * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with |
| 347 | * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, to flush last |
| 348 | * remaining bytes (if not multiple of 3). |
| 349 | * </p> |
| 350 | * <p><b>Note: no padding is added when encoding using the URL-safe alphabet.</b></p> |
| 351 | * <p> |
| 352 | * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. |
| 353 | * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ |
| 354 | * </p> |
| 355 | * |
| 356 | * @param in |
| 357 | * byte[] array of binary data to base64 encode. |
| 358 | * @param inPos |
| 359 | * Position to start reading data from. |
| 360 | * @param inAvail |
| 361 | * Amount of bytes available from input for encoding. |
| 362 | * @param context |
| 363 | * the context to be used |
| 364 | */ |
| 365 | @Override |
| 366 | void encode(final byte[] in, int inPos, final int inAvail, final Context context) { |
| 367 | if (context.eof) { |
| 368 | return; |
| 369 | } |
| 370 | // inAvail < 0 is how we're informed of EOF in the underlying data we're |
| 371 | // encoding. |
| 372 | if (inAvail < 0) { |
| 373 | context.eof = true; |
| 374 | if (0 == context.modulus && lineLength == 0) { |
| 375 | return; // no leftovers to process and not using chunking |
| 376 | } |
| 377 | final byte[] buffer = ensureBufferSize(encodeSize, context); |
| 378 | final int savedPos = context.pos; |
| 379 | switch (context.modulus) { // 0-2 |
| 380 | case 0 : // nothing to do here |
| 381 | break; |
| 382 | case 1 : // 8 bits = 6 + 2 |
| 383 | // top 6 bits: |
| 384 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS]; |
| 385 | // remaining 2: |
| 386 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS]; |
| 387 | // URL-SAFE skips the padding to further reduce size. |
| 388 | if (encodeTable == STANDARD_ENCODE_TABLE) { |
| 389 | buffer[context.pos++] = pad; |
| 390 | buffer[context.pos++] = pad; |
| 391 | } |
| 392 | break; |
| 393 | |
| 394 | case 2 : // 16 bits = 6 + 6 + 4 |
| 395 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS]; |
| 396 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS]; |
| 397 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS]; |
| 398 | // URL-SAFE skips the padding to further reduce size. |
| 399 | if (encodeTable == STANDARD_ENCODE_TABLE) { |
| 400 | buffer[context.pos++] = pad; |
| 401 | } |
| 402 | break; |
| 403 | default: |
| 404 | throw new IllegalStateException("Impossible modulus "+context.modulus); |
| 405 | } |
| 406 | context.currentLinePos += context.pos - savedPos; // keep track of current line position |
| 407 | // if currentPos == 0 we are at the start of a line, so don't add CRLF |
| 408 | if (lineLength > 0 && context.currentLinePos > 0) { |
| 409 | System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); |
| 410 | context.pos += lineSeparator.length; |
| 411 | } |
| 412 | } else { |
| 413 | for (int i = 0; i < inAvail; i++) { |
| 414 | final byte[] buffer = ensureBufferSize(encodeSize, context); |
| 415 | context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK; |
| 416 | int b = in[inPos++]; |
| 417 | if (b < 0) { |
| 418 | b += 256; |
| 419 | } |
| 420 | context.ibitWorkArea = (context.ibitWorkArea << 8) + b; // BITS_PER_BYTE |
| 421 | if (0 == context.modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract |
| 422 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS]; |
| 423 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS]; |
| 424 | buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS]; |
| 425 | buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS]; |
| 426 | context.currentLinePos += BYTES_PER_ENCODED_BLOCK; |
| 427 | if (lineLength > 0 && lineLength <= context.currentLinePos) { |
| 428 | System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); |
| 429 | context.pos += lineSeparator.length; |
| 430 | context.currentLinePos = 0; |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | /** |
| 438 | * <p> |
| 439 | * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once |
| 440 | * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1" |
| 441 | * call is not necessary when decoding, but it doesn't hurt, either. |
| 442 | * </p> |
| 443 | * <p> |
| 444 | * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are |
| 445 | * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in, |
| 446 | * garbage-out philosophy: it will not check the provided data for validity. |
| 447 | * </p> |
| 448 | * <p> |
| 449 | * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. |
| 450 | * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ |
| 451 | * </p> |
| 452 | * |
| 453 | * @param in |
| 454 | * byte[] array of ascii data to base64 decode. |
| 455 | * @param inPos |
| 456 | * Position to start reading data from. |
| 457 | * @param inAvail |
| 458 | * Amount of bytes available from input for encoding. |
| 459 | * @param context |
| 460 | * the context to be used |
| 461 | */ |
| 462 | @Override |
| 463 | void decode(final byte[] in, int inPos, final int inAvail, final Context context) { |
| 464 | if (context.eof) { |
| 465 | return; |
| 466 | } |
| 467 | if (inAvail < 0) { |
| 468 | context.eof = true; |
| 469 | } |
| 470 | for (int i = 0; i < inAvail; i++) { |
| 471 | final byte[] buffer = ensureBufferSize(decodeSize, context); |
| 472 | final byte b = in[inPos++]; |
| 473 | if (b == pad) { |
| 474 | // We're done. |
| 475 | context.eof = true; |
| 476 | break; |
| 477 | } else { |
| 478 | if (b >= 0 && b < DECODE_TABLE.length) { |
| 479 | final int result = DECODE_TABLE[b]; |
| 480 | if (result >= 0) { |
| 481 | context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK; |
| 482 | context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result; |
| 483 | if (context.modulus == 0) { |
| 484 | buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS); |
| 485 | buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); |
| 486 | buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS); |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | // Two forms of EOF as far as base64 decoder is concerned: actual |
| 494 | // EOF (-1) and first time '=' character is encountered in stream. |
| 495 | // This approach makes the '=' padding characters completely optional. |
| 496 | if (context.eof && context.modulus != 0) { |
| 497 | final byte[] buffer = ensureBufferSize(decodeSize, context); |
| 498 | |
| 499 | // We have some spare bits remaining |
| 500 | // Output all whole multiples of 8 bits and ignore the rest |
| 501 | switch (context.modulus) { |
| 502 | // case 0 : // impossible, as excluded above |
| 503 | case 1 : // 6 bits - ignore entirely |
| 504 | // TODO not currently tested; perhaps it is impossible? |
| 505 | break; |
| 506 | case 2 : // 12 bits = 8 + 4 |
| 507 | context.ibitWorkArea = context.ibitWorkArea >> 4; // dump the extra 4 bits |
| 508 | buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); |
| 509 | break; |
| 510 | case 3 : // 18 bits = 8 + 8 + 2 |
| 511 | context.ibitWorkArea = context.ibitWorkArea >> 2; // dump 2 bits |
| 512 | buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); |
| 513 | buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); |
| 514 | break; |
| 515 | default: |
| 516 | throw new IllegalStateException("Impossible modulus "+context.modulus); |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | /** |
| 522 | * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the |
| 523 | * method treats whitespace as valid. |
| 524 | * |
| 525 | * @param arrayOctet |
| 526 | * byte array to test |
| 527 | * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; |
| 528 | * <code>false</code>, otherwise |
| 529 | * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0. |
| 530 | */ |
| 531 | @Deprecated |
| 532 | public static boolean isArrayByteBase64(final byte[] arrayOctet) { |
| 533 | return isBase64(arrayOctet); |
| 534 | } |
| 535 | |
| 536 | /** |
| 537 | * Returns whether or not the <code>octet</code> is in the base 64 alphabet. |
| 538 | * |
| 539 | * @param octet |
| 540 | * The value to test |
| 541 | * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise. |
| 542 | * @since 1.4 |
| 543 | */ |
| 544 | public static boolean isBase64(final byte octet) { |
| 545 | return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1); |
| 546 | } |
| 547 | |
| 548 | /** |
| 549 | * Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the |
| 550 | * method treats whitespace as valid. |
| 551 | * |
| 552 | * @param base64 |
| 553 | * String to test |
| 554 | * @return <code>true</code> if all characters in the String are valid characters in the Base64 alphabet or if |
| 555 | * the String is empty; <code>false</code>, otherwise |
| 556 | * @since 1.5 |
| 557 | */ |
| 558 | public static boolean isBase64(final String base64) { |
| 559 | return isBase64(getBytesUtf8(base64)); |
| 560 | } |
| 561 | |
| 562 | /** |
| 563 | * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the |
| 564 | * method treats whitespace as valid. |
| 565 | * |
| 566 | * @param arrayOctet |
| 567 | * byte array to test |
| 568 | * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; |
| 569 | * <code>false</code>, otherwise |
| 570 | * @since 1.5 |
| 571 | */ |
| 572 | public static boolean isBase64(final byte[] arrayOctet) { |
| 573 | for (int i = 0; i < arrayOctet.length; i++) { |
| 574 | if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) { |
| 575 | return false; |
| 576 | } |
| 577 | } |
| 578 | return true; |
| 579 | } |
| 580 | |
| 581 | /** |
| 582 | * Encodes binary data using the base64 algorithm but does not chunk the output. |
| 583 | * |
| 584 | * @param binaryData |
| 585 | * binary data to encode |
| 586 | * @return byte[] containing Base64 characters in their UTF-8 representation. |
| 587 | */ |
| 588 | public static byte[] encodeBase64(final byte[] binaryData) { |
| 589 | return encodeBase64(binaryData, false); |
| 590 | } |
| 591 | |
| 592 | /** |
| 593 | * Encodes binary data using the base64 algorithm but does not chunk the output. |
| 594 | * |
| 595 | * NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to |
| 596 | * single-line non-chunking (commons-codec-1.5). |
| 597 | * |
| 598 | * @param binaryData |
| 599 | * binary data to encode |
| 600 | * @return String containing Base64 characters. |
| 601 | * @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not). |
| 602 | */ |
| 603 | public static String encodeBase64String(final byte[] binaryData) { |
| 604 | return newStringUtf8(encodeBase64(binaryData, false)); |
| 605 | } |
| 606 | |
| 607 | /** |
| 608 | * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The |
| 609 | * url-safe variation emits - and _ instead of + and / characters. |
| 610 | * <b>Note: no padding is added.</b> |
| 611 | * @param binaryData |
| 612 | * binary data to encode |
| 613 | * @return byte[] containing Base64 characters in their UTF-8 representation. |
| 614 | * @since 1.4 |
| 615 | */ |
| 616 | public static byte[] encodeBase64URLSafe(final byte[] binaryData) { |
| 617 | return encodeBase64(binaryData, false, true); |
| 618 | } |
| 619 | |
| 620 | /** |
| 621 | * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The |
| 622 | * url-safe variation emits - and _ instead of + and / characters. |
| 623 | * <b>Note: no padding is added.</b> |
| 624 | * @param binaryData |
| 625 | * binary data to encode |
| 626 | * @return String containing Base64 characters |
| 627 | * @since 1.4 |
| 628 | */ |
| 629 | public static String encodeBase64URLSafeString(final byte[] binaryData) { |
| 630 | return newStringUtf8(encodeBase64(binaryData, false, true)); |
| 631 | } |
| 632 | |
| 633 | /** |
| 634 | * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks |
| 635 | * |
| 636 | * @param binaryData |
| 637 | * binary data to encode |
| 638 | * @return Base64 characters chunked in 76 character blocks |
| 639 | */ |
| 640 | public static byte[] encodeBase64Chunked(final byte[] binaryData) { |
| 641 | return encodeBase64(binaryData, true); |
| 642 | } |
| 643 | |
| 644 | /** |
| 645 | * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. |
| 646 | * |
| 647 | * @param binaryData |
| 648 | * Array containing binary data to encode. |
| 649 | * @param isChunked |
| 650 | * if <code>true</code> this encoder will chunk the base64 output into 76 character blocks |
| 651 | * @return Base64-encoded data. |
| 652 | * @throws IllegalArgumentException |
| 653 | * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} |
| 654 | */ |
| 655 | public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) { |
| 656 | return encodeBase64(binaryData, isChunked, false); |
| 657 | } |
| 658 | |
| 659 | /** |
| 660 | * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. |
| 661 | * |
| 662 | * @param binaryData |
| 663 | * Array containing binary data to encode. |
| 664 | * @param isChunked |
| 665 | * if <code>true</code> this encoder will chunk the base64 output into 76 character blocks |
| 666 | * @param urlSafe |
| 667 | * if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters. |
| 668 | * <b>Note: no padding is added when encoding using the URL-safe alphabet.</b> |
| 669 | * @return Base64-encoded data. |
| 670 | * @throws IllegalArgumentException |
| 671 | * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} |
| 672 | * @since 1.4 |
| 673 | */ |
| 674 | public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) { |
| 675 | return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE); |
| 676 | } |
| 677 | |
| 678 | /** |
| 679 | * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. |
| 680 | * |
| 681 | * @param binaryData |
| 682 | * Array containing binary data to encode. |
| 683 | * @param isChunked |
| 684 | * if <code>true</code> this encoder will chunk the base64 output into 76 character blocks |
| 685 | * @param urlSafe |
| 686 | * if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters. |
| 687 | * <b>Note: no padding is added when encoding using the URL-safe alphabet.</b> |
| 688 | * @param maxResultSize |
| 689 | * The maximum result size to accept. |
| 690 | * @return Base64-encoded data. |
| 691 | * @throws IllegalArgumentException |
| 692 | * Thrown when the input array needs an output array bigger than maxResultSize |
| 693 | * @since 1.4 |
| 694 | */ |
| 695 | public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, |
| 696 | final boolean urlSafe, final int maxResultSize) { |
| 697 | if (binaryData == null || binaryData.length == 0) { |
| 698 | return binaryData; |
| 699 | } |
| 700 | |
| 701 | // Create this so can use the super-class method |
| 702 | // Also ensures that the same roundings are performed by the ctor and the code |
| 703 | final Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe); |
| 704 | final long len = b64.getEncodedLength(binaryData); |
| 705 | if (len > maxResultSize) { |
| 706 | throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + |
| 707 | len + |
| 708 | ") than the specified maximum size of " + |
| 709 | maxResultSize); |
| 710 | } |
| 711 | |
| 712 | return b64.encode(binaryData); |
| 713 | } |
| 714 | |
| 715 | /** |
| 716 | * Decodes a Base64 String into octets. |
| 717 | * <p> |
| 718 | * <b>Note:</b> this method seamlessly handles data encoded in URL-safe or normal mode. |
| 719 | * </p> |
| 720 | * |
| 721 | * @param base64String |
| 722 | * String containing Base64 data |
| 723 | * @return Array containing decoded data. |
| 724 | * @since 1.4 |
| 725 | */ |
| 726 | public static byte[] decodeBase64(final String base64String) { |
| 727 | return new Base64().decode(base64String); |
| 728 | } |
| 729 | |
| 730 | /** |
| 731 | * Decodes Base64 data into octets. |
| 732 | * <p> |
| 733 | * <b>Note:</b> this method seamlessly handles data encoded in URL-safe or normal mode. |
| 734 | * </p> |
| 735 | * |
| 736 | * @param base64Data |
| 737 | * Byte array containing Base64 data |
| 738 | * @return Array containing decoded data. |
| 739 | */ |
| 740 | public static byte[] decodeBase64(final byte[] base64Data) { |
| 741 | return new Base64().decode(base64Data); |
| 742 | } |
| 743 | |
| 744 | // Implementation of the Encoder Interface |
| 745 | |
| 746 | // Implementation of integer encoding used for crypto |
| 747 | /** |
| 748 | * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. |
| 749 | * |
| 750 | * @param pArray |
| 751 | * a byte array containing base64 character data |
| 752 | * @return A BigInteger |
| 753 | * @since 1.4 |
| 754 | */ |
| 755 | public static BigInteger decodeInteger(final byte[] pArray) { |
| 756 | return new BigInteger(1, decodeBase64(pArray)); |
| 757 | } |
| 758 | |
| 759 | /** |
| 760 | * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. |
| 761 | * |
| 762 | * @param bigInt |
| 763 | * a BigInteger |
| 764 | * @return A byte array containing base64 character data |
| 765 | * @throws NullPointerException |
| 766 | * if null is passed in |
| 767 | * @since 1.4 |
| 768 | */ |
| 769 | public static byte[] encodeInteger(final BigInteger bigInt) { |
| 770 | if (bigInt == null) { |
| 771 | throw new NullPointerException("encodeInteger called with null parameter"); |
| 772 | } |
| 773 | return encodeBase64(toIntegerBytes(bigInt), false); |
| 774 | } |
| 775 | |
| 776 | /** |
| 777 | * Returns a byte-array representation of a <code>BigInteger</code> without sign bit. |
| 778 | * |
| 779 | * @param bigInt |
| 780 | * <code>BigInteger</code> to be converted |
| 781 | * @return a byte array representation of the BigInteger parameter |
| 782 | */ |
| 783 | static byte[] toIntegerBytes(final BigInteger bigInt) { |
| 784 | int bitlen = bigInt.bitLength(); |
| 785 | // round bitlen |
| 786 | bitlen = ((bitlen + 7) >> 3) << 3; |
| 787 | final byte[] bigBytes = bigInt.toByteArray(); |
| 788 | |
| 789 | if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { |
| 790 | return bigBytes; |
| 791 | } |
| 792 | // set up params for copying everything but sign bit |
| 793 | int startSrc = 0; |
| 794 | int len = bigBytes.length; |
| 795 | |
| 796 | // if bigInt is exactly byte-aligned, just skip signbit in copy |
| 797 | if ((bigInt.bitLength() % 8) == 0) { |
| 798 | startSrc = 1; |
| 799 | len--; |
| 800 | } |
| 801 | final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec |
| 802 | final byte[] resizedBytes = new byte[bitlen / 8]; |
| 803 | System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len); |
| 804 | return resizedBytes; |
| 805 | } |
| 806 | |
| 807 | /** |
| 808 | * Returns whether or not the <code>octet</code> is in the Base64 alphabet. |
| 809 | * |
| 810 | * @param octet |
| 811 | * The value to test |
| 812 | * @return <code>true</code> if the value is defined in the the Base64 alphabet <code>false</code> otherwise. |
| 813 | */ |
| 814 | @Override |
| 815 | protected boolean isInAlphabet(final byte octet) { |
| 816 | return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1; |
| 817 | } |
| 818 | |
| 819 | } |