001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.commons.codec.binary;
019
020 import java.math.BigInteger;
021
022 /**
023 * Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
024 *
025 * <p>
026 * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
027 * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
028 * </p>
029 * <p>
030 * The class can be parameterized in the following manner with various constructors:
031 * <ul>
032 * <li>URL-safe mode: Default off.</li>
033 * <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of
034 * 4 in the encoded data.
035 * <li>Line separator: Default is CRLF ("\r\n")</li>
036 * </ul>
037 * </p>
038 * <p>
039 * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode
040 * character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
041 * </p>
042 * <p>
043 * This class is not thread-safe. Each thread should use its own instance.
044 * </p>
045 *
046 * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
047 * @author Apache Software Foundation
048 * @since 1.0
049 * @version $Revision: 1201529 $
050 */
051 public class Base64 extends BaseNCodec {
052
053 /**
054 * BASE32 characters are 6 bits in length.
055 * They are formed by taking a block of 3 octets to form a 24-bit string,
056 * which is converted into 4 BASE64 characters.
057 */
058 private static final int BITS_PER_ENCODED_BYTE = 6;
059 private static final int BYTES_PER_UNENCODED_BLOCK = 3;
060 private static final int BYTES_PER_ENCODED_BLOCK = 4;
061
062 /**
063 * Chunk separator per RFC 2045 section 2.1.
064 *
065 * <p>
066 * N.B. The next major release may break compatibility and make this field private.
067 * </p>
068 *
069 * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
070 */
071 static final byte[] CHUNK_SEPARATOR = {'\r', '\n'};
072
073 /**
074 * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
075 * equivalents as specified in Table 1 of RFC 2045.
076 *
077 * Thanks to "commons" project in ws.apache.org for this code.
078 * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
079 */
080 private static final byte[] STANDARD_ENCODE_TABLE = {
081 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
082 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
083 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
084 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
085 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
086 };
087
088 /**
089 * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and /
090 * changed to - and _ to make the encoded Base64 results more URL-SAFE.
091 * This table is only used when the Base64's mode is set to URL-SAFE.
092 */
093 private static final byte[] URL_SAFE_ENCODE_TABLE = {
094 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
095 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
096 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
097 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
098 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
099 };
100
101 /**
102 * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in
103 * Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
104 * alphabet but fall within the bounds of the array are translated to -1.
105 *
106 * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
107 * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
108 *
109 * Thanks to "commons" project in ws.apache.org for this code.
110 * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
111 */
112 private static final byte[] DECODE_TABLE = {
113 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
114 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
115 -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54,
116 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
117 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
118 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
119 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
120 };
121
122 /**
123 * Base64 uses 6-bit fields.
124 */
125 /** Mask used to extract 6 bits, used when encoding */
126 private static final int MASK_6BITS = 0x3f;
127
128 // The static final fields above are used for the original static byte[] methods on Base64.
129 // The private member fields below are used with the new streaming approach, which requires
130 // some state be preserved between calls of encode() and decode().
131
132 /**
133 * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able
134 * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch
135 * between the two modes.
136 */
137 private final byte[] encodeTable;
138
139 // Only one decode table currently; keep for consistency with Base32 code
140 private final byte[] decodeTable = DECODE_TABLE;
141
142 /**
143 * Line separator for encoding. Not used when decoding. Only used if lineLength > 0.
144 */
145 private final byte[] lineSeparator;
146
147 /**
148 * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
149 * <code>decodeSize = 3 + lineSeparator.length;</code>
150 */
151 private final int decodeSize;
152
153 /**
154 * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
155 * <code>encodeSize = 4 + lineSeparator.length;</code>
156 */
157 private final int encodeSize;
158
159 /**
160 * Place holder for the bytes we're dealing with for our based logic.
161 * Bitwise operations store and extract the encoding or decoding from this variable.
162 */
163 private int bitWorkArea;
164
165 /**
166 * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
167 * <p>
168 * When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE.
169 * </p>
170 *
171 * <p>
172 * When decoding all variants are supported.
173 * </p>
174 */
175 public Base64() {
176 this(0);
177 }
178
179 /**
180 * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.
181 * <p>
182 * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
183 * </p>
184 *
185 * <p>
186 * When decoding all variants are supported.
187 * </p>
188 *
189 * @param urlSafe
190 * if <code>true</code>, URL-safe encoding is used. In most cases this should be set to
191 * <code>false</code>.
192 * @since 1.4
193 */
194 public Base64(boolean urlSafe) {
195 this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe);
196 }
197
198 /**
199 * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
200 * <p>
201 * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is
202 * STANDARD_ENCODE_TABLE.
203 * </p>
204 * <p>
205 * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
206 * </p>
207 * <p>
208 * When decoding all variants are supported.
209 * </p>
210 *
211 * @param lineLength
212 * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
213 * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
214 * @since 1.4
215 */
216 public Base64(int lineLength) {
217 this(lineLength, CHUNK_SEPARATOR);
218 }
219
220 /**
221 * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
222 * <p>
223 * When encoding the line length and line separator are given in the constructor, and the encoding table is
224 * STANDARD_ENCODE_TABLE.
225 * </p>
226 * <p>
227 * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
228 * </p>
229 * <p>
230 * When decoding all variants are supported.
231 * </p>
232 *
233 * @param lineLength
234 * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
235 * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
236 * @param lineSeparator
237 * Each line of encoded data will end with this sequence of bytes.
238 * @throws IllegalArgumentException
239 * Thrown when the provided lineSeparator included some base64 characters.
240 * @since 1.4
241 */
242 public Base64(int lineLength, byte[] lineSeparator) {
243 this(lineLength, lineSeparator, false);
244 }
245
246 /**
247 * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
248 * <p>
249 * When encoding the line length and line separator are given in the constructor, and the encoding table is
250 * STANDARD_ENCODE_TABLE.
251 * </p>
252 * <p>
253 * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
254 * </p>
255 * <p>
256 * When decoding all variants are supported.
257 * </p>
258 *
259 * @param lineLength
260 * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
261 * If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
262 * @param lineSeparator
263 * Each line of encoded data will end with this sequence of bytes.
264 * @param urlSafe
265 * Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
266 * operations. Decoding seamlessly handles both modes.
267 * @throws IllegalArgumentException
268 * The provided lineSeparator included some base64 characters. That's not going to work!
269 * @since 1.4
270 */
271 public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
272 super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK,
273 lineLength,
274 lineSeparator == null ? 0 : lineSeparator.length);
275 // TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
276 // @see test case Base64Test.testConstructors()
277 if (lineSeparator != null) {
278 if (containsAlphabetOrPad(lineSeparator)) {
279 String sep = StringUtils.newStringUtf8(lineSeparator);
280 throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
281 }
282 if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE
283 this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
284 this.lineSeparator = new byte[lineSeparator.length];
285 System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
286 } else {
287 this.encodeSize = BYTES_PER_ENCODED_BLOCK;
288 this.lineSeparator = null;
289 }
290 } else {
291 this.encodeSize = BYTES_PER_ENCODED_BLOCK;
292 this.lineSeparator = null;
293 }
294 this.decodeSize = this.encodeSize - 1;
295 this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;
296 }
297
298 /**
299 * Returns our current encode mode. True if we're URL-SAFE, false otherwise.
300 *
301 * @return true if we're in URL-SAFE mode, false otherwise.
302 * @since 1.4
303 */
304 public boolean isUrlSafe() {
305 return this.encodeTable == URL_SAFE_ENCODE_TABLE;
306 }
307
308 /**
309 * <p>
310 * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
311 * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush last
312 * remaining bytes (if not multiple of 3).
313 * </p>
314 * <p>
315 * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
316 * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
317 * </p>
318 *
319 * @param in
320 * byte[] array of binary data to base64 encode.
321 * @param inPos
322 * Position to start reading data from.
323 * @param inAvail
324 * Amount of bytes available from input for encoding.
325 */
326 @Override
327 void encode(byte[] in, int inPos, int inAvail) {
328 if (eof) {
329 return;
330 }
331 // inAvail < 0 is how we're informed of EOF in the underlying data we're
332 // encoding.
333 if (inAvail < 0) {
334 eof = true;
335 if (0 == modulus && lineLength == 0) {
336 return; // no leftovers to process and not using chunking
337 }
338 ensureBufferSize(encodeSize);
339 int savedPos = pos;
340 switch (modulus) { // 0-2
341 case 1 : // 8 bits = 6 + 2
342 buffer[pos++] = encodeTable[(bitWorkArea >> 2) & MASK_6BITS]; // top 6 bits
343 buffer[pos++] = encodeTable[(bitWorkArea << 4) & MASK_6BITS]; // remaining 2
344 // URL-SAFE skips the padding to further reduce size.
345 if (encodeTable == STANDARD_ENCODE_TABLE) {
346 buffer[pos++] = PAD;
347 buffer[pos++] = PAD;
348 }
349 break;
350
351 case 2 : // 16 bits = 6 + 6 + 4
352 buffer[pos++] = encodeTable[(bitWorkArea >> 10) & MASK_6BITS];
353 buffer[pos++] = encodeTable[(bitWorkArea >> 4) & MASK_6BITS];
354 buffer[pos++] = encodeTable[(bitWorkArea << 2) & MASK_6BITS];
355 // URL-SAFE skips the padding to further reduce size.
356 if (encodeTable == STANDARD_ENCODE_TABLE) {
357 buffer[pos++] = PAD;
358 }
359 break;
360 }
361 currentLinePos += pos - savedPos; // keep track of current line position
362 // if currentPos == 0 we are at the start of a line, so don't add CRLF
363 if (lineLength > 0 && currentLinePos > 0) {
364 System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
365 pos += lineSeparator.length;
366 }
367 } else {
368 for (int i = 0; i < inAvail; i++) {
369 ensureBufferSize(encodeSize);
370 modulus = (modulus+1) % BYTES_PER_UNENCODED_BLOCK;
371 int b = in[inPos++];
372 if (b < 0) {
373 b += 256;
374 }
375 bitWorkArea = (bitWorkArea << 8) + b; // BITS_PER_BYTE
376 if (0 == modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract
377 buffer[pos++] = encodeTable[(bitWorkArea >> 18) & MASK_6BITS];
378 buffer[pos++] = encodeTable[(bitWorkArea >> 12) & MASK_6BITS];
379 buffer[pos++] = encodeTable[(bitWorkArea >> 6) & MASK_6BITS];
380 buffer[pos++] = encodeTable[bitWorkArea & MASK_6BITS];
381 currentLinePos += BYTES_PER_ENCODED_BLOCK;
382 if (lineLength > 0 && lineLength <= currentLinePos) {
383 System.arraycopy(lineSeparator, 0, buffer, pos, lineSeparator.length);
384 pos += lineSeparator.length;
385 currentLinePos = 0;
386 }
387 }
388 }
389 }
390 }
391
392 /**
393 * <p>
394 * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
395 * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
396 * call is not necessary when decoding, but it doesn't hurt, either.
397 * </p>
398 * <p>
399 * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
400 * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
401 * garbage-out philosophy: it will not check the provided data for validity.
402 * </p>
403 * <p>
404 * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
405 * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
406 * </p>
407 *
408 * @param in
409 * byte[] array of ascii data to base64 decode.
410 * @param inPos
411 * Position to start reading data from.
412 * @param inAvail
413 * Amount of bytes available from input for encoding.
414 */
415 @Override
416 void decode(byte[] in, int inPos, int inAvail) {
417 if (eof) {
418 return;
419 }
420 if (inAvail < 0) {
421 eof = true;
422 }
423 for (int i = 0; i < inAvail; i++) {
424 ensureBufferSize(decodeSize);
425 byte b = in[inPos++];
426 if (b == PAD) {
427 // We're done.
428 eof = true;
429 break;
430 } else {
431 if (b >= 0 && b < DECODE_TABLE.length) {
432 int result = DECODE_TABLE[b];
433 if (result >= 0) {
434 modulus = (modulus+1) % BYTES_PER_ENCODED_BLOCK;
435 bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result;
436 if (modulus == 0) {
437 buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
438 buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
439 buffer[pos++] = (byte) (bitWorkArea & MASK_8BITS);
440 }
441 }
442 }
443 }
444 }
445
446 // Two forms of EOF as far as base64 decoder is concerned: actual
447 // EOF (-1) and first time '=' character is encountered in stream.
448 // This approach makes the '=' padding characters completely optional.
449 if (eof && modulus != 0) {
450 ensureBufferSize(decodeSize);
451
452 // We have some spare bits remaining
453 // Output all whole multiples of 8 bits and ignore the rest
454 switch (modulus) {
455 // case 1: // 6 bits - ignore entirely
456 // break;
457 case 2 : // 12 bits = 8 + 4
458 bitWorkArea = bitWorkArea >> 4; // dump the extra 4 bits
459 buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
460 break;
461 case 3 : // 18 bits = 8 + 8 + 2
462 bitWorkArea = bitWorkArea >> 2; // dump 2 bits
463 buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
464 buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
465 break;
466 }
467 }
468 }
469
470 /**
471 * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
472 * method treats whitespace as valid.
473 *
474 * @param arrayOctet
475 * byte array to test
476 * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
477 * <code>false</code>, otherwise
478 * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
479 */
480 public static boolean isArrayByteBase64(byte[] arrayOctet) {
481 return isBase64(arrayOctet);
482 }
483
484 /**
485 * Returns whether or not the <code>octet</code> is in the base 64 alphabet.
486 *
487 * @param octet
488 * The value to test
489 * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
490 * @since 1.4
491 */
492 public static boolean isBase64(byte octet) {
493 return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1);
494 }
495
496 /**
497 * Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the
498 * method treats whitespace as valid.
499 *
500 * @param base64
501 * String to test
502 * @return <code>true</code> if all characters in the String are valid characters in the Base64 alphabet or if
503 * the String is empty; <code>false</code>, otherwise
504 * @since 1.5
505 */
506 public static boolean isBase64(String base64) {
507 return isBase64(StringUtils.getBytesUtf8(base64));
508 }
509
510 /**
511 * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
512 * method treats whitespace as valid.
513 *
514 * @param arrayOctet
515 * byte array to test
516 * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
517 * <code>false</code>, otherwise
518 * @since 1.5
519 */
520 public static boolean isBase64(byte[] arrayOctet) {
521 for (int i = 0; i < arrayOctet.length; i++) {
522 if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) {
523 return false;
524 }
525 }
526 return true;
527 }
528
529 /**
530 * Encodes binary data using the base64 algorithm but does not chunk the output.
531 *
532 * @param binaryData
533 * binary data to encode
534 * @return byte[] containing Base64 characters in their UTF-8 representation.
535 */
536 public static byte[] encodeBase64(byte[] binaryData) {
537 return encodeBase64(binaryData, false);
538 }
539
540 /**
541 * Encodes binary data using the base64 algorithm but does not chunk the output.
542 *
543 * NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to
544 * single-line non-chunking (commons-codec-1.5).
545 *
546 * @param binaryData
547 * binary data to encode
548 * @return String containing Base64 characters.
549 * @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not).
550 */
551 public static String encodeBase64String(byte[] binaryData) {
552 return StringUtils.newStringUtf8(encodeBase64(binaryData, false));
553 }
554
555 /**
556 * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
557 * url-safe variation emits - and _ instead of + and / characters.
558 *
559 * @param binaryData
560 * binary data to encode
561 * @return byte[] containing Base64 characters in their UTF-8 representation.
562 * @since 1.4
563 */
564 public static byte[] encodeBase64URLSafe(byte[] binaryData) {
565 return encodeBase64(binaryData, false, true);
566 }
567
568 /**
569 * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The
570 * url-safe variation emits - and _ instead of + and / characters.
571 *
572 * @param binaryData
573 * binary data to encode
574 * @return String containing Base64 characters
575 * @since 1.4
576 */
577 public static String encodeBase64URLSafeString(byte[] binaryData) {
578 return StringUtils.newStringUtf8(encodeBase64(binaryData, false, true));
579 }
580
581 /**
582 * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
583 *
584 * @param binaryData
585 * binary data to encode
586 * @return Base64 characters chunked in 76 character blocks
587 */
588 public static byte[] encodeBase64Chunked(byte[] binaryData) {
589 return encodeBase64(binaryData, true);
590 }
591
592 /**
593 * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
594 *
595 * @param binaryData
596 * Array containing binary data to encode.
597 * @param isChunked
598 * if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
599 * @return Base64-encoded data.
600 * @throws IllegalArgumentException
601 * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
602 */
603 public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
604 return encodeBase64(binaryData, isChunked, false);
605 }
606
607 /**
608 * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
609 *
610 * @param binaryData
611 * Array containing binary data to encode.
612 * @param isChunked
613 * if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
614 * @param urlSafe
615 * if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
616 * @return Base64-encoded data.
617 * @throws IllegalArgumentException
618 * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
619 * @since 1.4
620 */
621 public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe) {
622 return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE);
623 }
624
625 /**
626 * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
627 *
628 * @param binaryData
629 * Array containing binary data to encode.
630 * @param isChunked
631 * if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
632 * @param urlSafe
633 * if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
634 * @param maxResultSize
635 * The maximum result size to accept.
636 * @return Base64-encoded data.
637 * @throws IllegalArgumentException
638 * Thrown when the input array needs an output array bigger than maxResultSize
639 * @since 1.4
640 */
641 public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
642 if (binaryData == null || binaryData.length == 0) {
643 return binaryData;
644 }
645
646 // Create this so can use the super-class method
647 // Also ensures that the same roundings are performed by the ctor and the code
648 Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
649 long len = b64.getEncodedLength(binaryData);
650 if (len > maxResultSize) {
651 throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
652 len +
653 ") than the specified maximum size of " +
654 maxResultSize);
655 }
656
657 return b64.encode(binaryData);
658 }
659
660 /**
661 * Decodes a Base64 String into octets
662 *
663 * @param base64String
664 * String containing Base64 data
665 * @return Array containing decoded data.
666 * @since 1.4
667 */
668 public static byte[] decodeBase64(String base64String) {
669 return new Base64().decode(base64String);
670 }
671
672 /**
673 * Decodes Base64 data into octets
674 *
675 * @param base64Data
676 * Byte array containing Base64 data
677 * @return Array containing decoded data.
678 */
679 public static byte[] decodeBase64(byte[] base64Data) {
680 return new Base64().decode(base64Data);
681 }
682
683 // Implementation of the Encoder Interface
684
685 // Implementation of integer encoding used for crypto
686 /**
687 * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
688 *
689 * @param pArray
690 * a byte array containing base64 character data
691 * @return A BigInteger
692 * @since 1.4
693 */
694 public static BigInteger decodeInteger(byte[] pArray) {
695 return new BigInteger(1, decodeBase64(pArray));
696 }
697
698 /**
699 * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
700 *
701 * @param bigInt
702 * a BigInteger
703 * @return A byte array containing base64 character data
704 * @throws NullPointerException
705 * if null is passed in
706 * @since 1.4
707 */
708 public static byte[] encodeInteger(BigInteger bigInt) {
709 if (bigInt == null) {
710 throw new NullPointerException("encodeInteger called with null parameter");
711 }
712 return encodeBase64(toIntegerBytes(bigInt), false);
713 }
714
715 /**
716 * Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
717 *
718 * @param bigInt
719 * <code>BigInteger</code> to be converted
720 * @return a byte array representation of the BigInteger parameter
721 */
722 static byte[] toIntegerBytes(BigInteger bigInt) {
723 int bitlen = bigInt.bitLength();
724 // round bitlen
725 bitlen = ((bitlen + 7) >> 3) << 3;
726 byte[] bigBytes = bigInt.toByteArray();
727
728 if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
729 return bigBytes;
730 }
731 // set up params for copying everything but sign bit
732 int startSrc = 0;
733 int len = bigBytes.length;
734
735 // if bigInt is exactly byte-aligned, just skip signbit in copy
736 if ((bigInt.bitLength() % 8) == 0) {
737 startSrc = 1;
738 len--;
739 }
740 int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
741 byte[] resizedBytes = new byte[bitlen / 8];
742 System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
743 return resizedBytes;
744 }
745
746 /**
747 * Returns whether or not the <code>octet</code> is in the Base32 alphabet.
748 *
749 * @param octet
750 * The value to test
751 * @return <code>true</code> if the value is defined in the the Base32 alphabet <code>false</code> otherwise.
752 */
753 @Override
754 protected boolean isInAlphabet(byte octet) {
755 return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
756 }
757
758 }