Debian Codegraph @

src/main/java/ezvcard/util/org/apache/commons/codec/binary/BaseNCodec.java

raw symbols SCIP
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.io.UnsupportedEncodingException;
50 import java.util.Arrays;
51
52 import ezvcard.util.org.apache.commons.codec.DecoderException;
53 import ezvcard.util.org.apache.commons.codec.EncoderException;
54
55 /**
56 * Abstract superclass for Base-N encoders and decoders.
57 *
58 * <p>
59 * This class is thread-safe.
60 * </p>
61 * <p>
62 * <b><i>ez-vcard integration note</i></b>: Minor modifications were made to this class so that it could be
63 * incorporated into the ez-vcard code base. Defining the Apache Commons Codec library as a project dependency causes
64 * an issue with Android devices, which is why parts of its source code have been directly incorporated into the
65 * ez-vcard code base.
66 * </p>
67 *
68 * @version $Id: BaseNCodec.java 1634404 2014-10-26 23:06:10Z ggregory $
69 */
70 public abstract class BaseNCodec {
71
72 /**
73 * Holds thread context so classes can be thread-safe.
74 *
75 * This class is not itself thread-safe; each thread must allocate its own copy.
76 *
77 * @since 1.7
78 */
79 static class Context {
80
81 /**
82 * Place holder for the bytes we're dealing with for our based logic.
83 * Bitwise operations store and extract the encoding or decoding from this variable.
84 */
85 int ibitWorkArea;
86
87 /**
88 * Place holder for the bytes we're dealing with for our based logic.
89 * Bitwise operations store and extract the encoding or decoding from this variable.
90 */
91 long lbitWorkArea;
92
93 /**
94 * Buffer for streaming.
95 */
96 byte[] buffer;
97
98 /**
99 * Position where next character should be written in the buffer.
100 */
101 int pos;
102
103 /**
104 * Position where next character should be read from the buffer.
105 */
106 int readPos;
107
108 /**
109 * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless,
110 * and must be thrown away.
111 */
112 boolean eof;
113
114 /**
115 * Variable tracks how many characters have been written to the current line. Only used when encoding. We use
116 * it to make sure each encoded line never goes beyond lineLength (if lineLength &gt; 0).
117 */
118 int currentLinePos;
119
120 /**
121 * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This
122 * variable helps track that.
123 */
124 int modulus;
125
126 Context() {
127 }
128
129 /**
130 * Returns a String useful for debugging (especially within a debugger.)
131 *
132 * @return a String useful for debugging.
133 */
134 @SuppressWarnings("boxing") // OK to ignore boxing here
135 @Override
136 public String toString() {
137 return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " +
138 "modulus=%s, pos=%s, readPos=%s]", this.getClass().getSimpleName(), Arrays.toString(buffer),
139 currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
140 }
141 }
142
143 /**
144 * EOF
145 *
146 * @since 1.7
147 */
148 static final int EOF = -1;
149
150 /**
151 * MIME chunk size per RFC 2045 section 6.8.
152 *
153 * <p>
154 * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
155 * equal signs.
156 * </p>
157 *
158 * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
159 */
160 public static final int MIME_CHUNK_SIZE = 76;
161
162 /**
163 * PEM chunk size per RFC 1421 section 4.3.2.4.
164 *
165 * <p>
166 * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
167 * equal signs.
168 * </p>
169 *
170 * @see <a href="http://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a>
171 */
172 public static final int PEM_CHUNK_SIZE = 64;
173
174 private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
175
176 /**
177 * Defines the default buffer size - currently {@value}
178 * - must be large enough for at least one encoded block+separator
179 */
180 private static final int DEFAULT_BUFFER_SIZE = 8192;
181
182 /** Mask used to extract 8 bits, used in decoding bytes */
183 protected static final int MASK_8BITS = 0xff;
184
185 /**
186 * Byte used to pad output.
187 */
188 protected static final byte PAD_DEFAULT = '='; // Allow static access to default
189
190 /**
191 * @deprecated Use {@link #pad}. Will be removed in 2.0.
192 */
193 @Deprecated
194 protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
195
196 protected final byte pad; // instance variable just in case it needs to vary later
197
198 /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
199 private final int unencodedBlockSize;
200
201 /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
202 private final int encodedBlockSize;
203
204 /**
205 * Chunksize for encoding. Not used when decoding.
206 * A value of zero or less implies no chunking of the encoded data.
207 * Rounded down to nearest multiple of encodedBlockSize.
208 */
209 protected final int lineLength;
210
211 /**
212 * Size of chunk separator. Not used unless {@link #lineLength} &gt; 0.
213 */
214 private final int chunkSeparatorLength;
215
216 /**
217 * Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize}
218 * If <code>chunkSeparatorLength</code> is zero, then chunking is disabled.
219 * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
220 * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
221 * @param lineLength if &gt; 0, use chunking with a length <code>lineLength</code>
222 * @param chunkSeparatorLength the chunk separator length, if relevant
223 */
224 protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize,
225 final int lineLength, final int chunkSeparatorLength) {
226 this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT);
227 }
228
229 /**
230 * Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize}
231 * If <code>chunkSeparatorLength</code> is zero, then chunking is disabled.
232 * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
233 * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
234 * @param lineLength if &gt; 0, use chunking with a length <code>lineLength</code>
235 * @param chunkSeparatorLength the chunk separator length, if relevant
236 * @param pad byte used as padding byte.
237 */
238 protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize,
239 final int lineLength, final int chunkSeparatorLength, final byte pad) {
240 this.unencodedBlockSize = unencodedBlockSize;
241 this.encodedBlockSize = encodedBlockSize;
242 final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
243 this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
244 this.chunkSeparatorLength = chunkSeparatorLength;
245
246 this.pad = pad;
247 }
248
249 /**
250 * Returns true if this object has buffered data for reading.
251 *
252 * @param context the context to be used
253 * @return true if there is data still available for reading.
254 */
255 boolean hasData(final Context context) { // package protected for access from I/O streams
256 return context.buffer != null;
257 }
258
259 /**
260 * Returns the amount of buffered data available for reading.
261 *
262 * @param context the context to be used
263 * @return The amount of buffered data available for reading.
264 */
265 int available(final Context context) { // package protected for access from I/O streams
266 return context.buffer != null ? context.pos - context.readPos : 0;
267 }
268
269 /**
270 * Get the default buffer size. Can be overridden.
271 *
272 * @return {@link #DEFAULT_BUFFER_SIZE}
273 */
274 protected int getDefaultBufferSize() {
275 return DEFAULT_BUFFER_SIZE;
276 }
277
278 /**
279 * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
280 * @param context the context to be used
281 */
282 private byte[] resizeBuffer(final Context context) {
283 if (context.buffer == null) {
284 context.buffer = new byte[getDefaultBufferSize()];
285 context.pos = 0;
286 context.readPos = 0;
287 } else {
288 final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR];
289 System.arraycopy(context.buffer, 0, b, 0, context.buffer.length);
290 context.buffer = b;
291 }
292 return context.buffer;
293 }
294
295 /**
296 * Ensure that the buffer has room for <code>size</code> bytes
297 *
298 * @param size minimum spare space required
299 * @param context the context to be used
300 * @return the buffer
301 */
302 protected byte[] ensureBufferSize(final int size, final Context context){
303 if ((context.buffer == null) || (context.buffer.length < context.pos + size)){
304 return resizeBuffer(context);
305 }
306 return context.buffer;
307 }
308
309 /**
310 * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
311 * bytes. Returns how many bytes were actually extracted.
312 * <p>
313 * Package protected for access from I/O streams.
314 *
315 * @param b
316 * byte[] array to extract the buffered data into.
317 * @param bPos
318 * position in byte[] array to start extraction at.
319 * @param bAvail
320 * amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
321 * @param context
322 * the context to be used
323 * @return The number of bytes successfully extracted into the provided byte[] array.
324 */
325 int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
326 if (context.buffer != null) {
327 final int len = Math.min(available(context), bAvail);
328 System.arraycopy(context.buffer, context.readPos, b, bPos, len);
329 context.readPos += len;
330 if (context.readPos >= context.pos) {
331 context.buffer = null; // so hasData() will return false, and this method can return -1
332 }
333 return len;
334 }
335 return context.eof ? EOF : 0;
336 }
337
338 /**
339 * Checks if a byte value is whitespace or not.
340 * Whitespace is taken to mean: space, tab, CR, LF
341 * @param byteToCheck
342 * the byte to check
343 * @return true if byte is whitespace, false otherwise
344 */
345 protected static boolean isWhiteSpace(final byte byteToCheck) {
346 switch (byteToCheck) {
347 case ' ' :
348 case '\n' :
349 case '\r' :
350 case '\t' :
351 return true;
352 default :
353 return false;
354 }
355 }
356
357 /**
358 * Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
359 * the Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
360 *
361 * @param obj
362 * Object to encode
363 * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
364 * @throws EncoderException
365 * if the parameter supplied is not of type byte[]
366 */
367 public Object encode(final Object obj) throws EncoderException {
368 if (!(obj instanceof byte[])) {
369 throw new EncoderException("Parameter supplied to Base-N encode is not a byte[]");
370 }
371 return encode((byte[]) obj);
372 }
373
374 /**
375 * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
376 * Uses UTF8 encoding.
377 *
378 * @param pArray
379 * a byte array containing binary data
380 * @return A String containing only Base-N character data
381 */
382 public String encodeToString(final byte[] pArray) {
383 return newStringUtf8(encode(pArray));
384 }
385
386 /**
387 * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet.
388 * Uses UTF8 encoding.
389 *
390 * @param pArray a byte array containing binary data
391 * @return String containing only character data in the appropriate alphabet.
392 */
393 public String encodeAsString(final byte[] pArray){
394 return newStringUtf8(encode(pArray));
395 }
396
397 /**
398 * Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
399 * the Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
400 *
401 * @param obj
402 * Object to decode
403 * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String
404 * supplied.
405 * @throws DecoderException
406 * if the parameter supplied is not of type byte[]
407 */
408 public Object decode(final Object obj) throws DecoderException {
409 if (obj instanceof byte[]) {
410 return decode((byte[]) obj);
411 } else if (obj instanceof String) {
412 return decode((String) obj);
413 } else {
414 throw new DecoderException("Parameter supplied to Base-N decode is not a byte[] or a String");
415 }
416 }
417
418 /**
419 * Decodes a String containing characters in the Base-N alphabet.
420 *
421 * @param pArray
422 * A String containing Base-N character data
423 * @return a byte array containing binary data
424 */
425 public byte[] decode(final String pArray) {
426 return decode(getBytesUtf8(pArray));
427 }
428
429 /**
430 * Decodes a byte[] containing characters in the Base-N alphabet.
431 *
432 * @param pArray
433 * A byte array containing Base-N character data
434 * @return a byte array containing binary data
435 */
436 public byte[] decode(final byte[] pArray) {
437 if (pArray == null || pArray.length == 0) {
438 return pArray;
439 }
440 final Context context = new Context();
441 decode(pArray, 0, pArray.length, context);
442 decode(pArray, 0, EOF, context); // Notify decoder of EOF.
443 final byte[] result = new byte[context.pos];
444 readResults(result, 0, result.length, context);
445 return result;
446 }
447
448 /**
449 * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
450 *
451 * @param pArray
452 * a byte array containing binary data
453 * @return A byte array containing only the basen alphabetic character data
454 */
455 public byte[] encode(final byte[] pArray) {
456 if (pArray == null || pArray.length == 0) {
457 return pArray;
458 }
459 final Context context = new Context();
460 encode(pArray, 0, pArray.length, context);
461 encode(pArray, 0, EOF, context); // Notify encoder of EOF.
462 final byte[] buf = new byte[context.pos - context.readPos];
463 readResults(buf, 0, buf.length, context);
464 return buf;
465 }
466
467 // package protected for access from I/O streams
468 abstract void encode(byte[] pArray, int i, int length, Context context);
469
470 // package protected for access from I/O streams
471 abstract void decode(byte[] pArray, int i, int length, Context context);
472
473 /**
474 * Returns whether or not the <code>octet</code> is in the current alphabet.
475 * Does not allow whitespace or pad.
476 *
477 * @param value The value to test
478 *
479 * @return <code>true</code> if the value is defined in the current alphabet, <code>false</code> otherwise.
480 */
481 protected abstract boolean isInAlphabet(byte value);
482
483 /**
484 * Tests a given byte array to see if it contains only valid characters within the alphabet.
485 * The method optionally treats whitespace and pad as valid.
486 *
487 * @param arrayOctet byte array to test
488 * @param allowWSPad if <code>true</code>, then whitespace and PAD are also allowed
489 *
490 * @return <code>true</code> if all bytes are valid characters in the alphabet or if the byte array is empty;
491 * <code>false</code>, otherwise
492 */
493 public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) {
494 for (int i = 0; i < arrayOctet.length; i++) {
495 if (!isInAlphabet(arrayOctet[i]) &&
496 (!allowWSPad || (arrayOctet[i] != pad) && !isWhiteSpace(arrayOctet[i]))) {
497 return false;
498 }
499 }
500 return true;
501 }
502
503 /**
504 * Tests a given String to see if it contains only valid characters within the alphabet.
505 * The method treats whitespace and PAD as valid.
506 *
507 * @param basen String to test
508 * @return <code>true</code> if all characters in the String are valid characters in the alphabet or if
509 * the String is empty; <code>false</code>, otherwise
510 * @see #isInAlphabet(byte[], boolean)
511 */
512 public boolean isInAlphabet(final String basen) {
513 return isInAlphabet(getBytesUtf8(basen), true);
514 }
515
516 /**
517 * Tests a given byte array to see if it contains any characters within the alphabet or PAD.
518 *
519 * Intended for use in checking line-ending arrays
520 *
521 * @param arrayOctet
522 * byte array to test
523 * @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> otherwise
524 */
525 protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
526 if (arrayOctet == null) {
527 return false;
528 }
529 for (final byte element : arrayOctet) {
530 if (pad == element || isInAlphabet(element)) {
531 return true;
532 }
533 }
534 return false;
535 }
536
537 /**
538 * Calculates the amount of space needed to encode the supplied array.
539 *
540 * @param pArray byte[] array which will later be encoded
541 *
542 * @return amount of space needed to encoded the supplied array.
543 * Returns a long since a max-len array will require &gt; Integer.MAX_VALUE
544 */
545 public long getEncodedLength(final byte[] pArray) {
546 // Calculate non-chunked size - rounded up to allow for padding
547 // cast to long is needed to avoid possibility of overflow
548 long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
549 if (lineLength > 0) { // We're using chunking
550 // Round up to nearest multiple
551 len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
552 }
553 return len;
554 }
555
556 /**
557 * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
558 * array.
559 *
560 * @param string
561 * the String to encode, may be <code>null</code>
562 * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
563 */
564 protected static byte[] getBytesUtf8(final String string) {
565 if (string == null) {
566 return null;
567 }
568
569 try {
570 return string.getBytes("UTF-8");
571 } catch (UnsupportedEncodingException e) {
572 //should never be thrown because all JVMs must support UTF-8
573 throw new RuntimeException(e);
574 }
575 }
576
577 /**
578 * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-8 charset.
579 *
580 * @param bytes
581 * The bytes to be decoded into characters
582 * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-8 charset,
583 * or <code>null</code> if the input byte array was <code>null</code>.
584 */
585 protected static String newStringUtf8(final byte[] bytes) {
586 if (bytes == null) {
587 return null;
588 }
589
590 try {
591 return new String(bytes, "UTF-8");
592 } catch (UnsupportedEncodingException e) {
593 //should never be thrown because all JVMs must support UTF-8
594 throw new RuntimeException(e);
595 }
596 }
597 }