Source code

    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
    018package org.apache.commons.codec.binary;
    019
    020/**
    021 * Provides Base32 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>.
    022 *
    023 * <p>
    024 * The class can be parameterized in the following manner with various constructors:
    025 * </p>
    026 * <ul>
    027 * <li>Whether to use the "base32hex" variant instead of the default "base32"</li>
    028 * <li>Line length: Default 76. Line length that aren't multiples of 8 will still essentially end up being multiples of
    029 * 8 in the encoded data.
    030 * <li>Line separator: Default is CRLF ("\r\n")</li>
    031 * </ul>
    032 * <p>
    033 * This class operates directly on byte streams, and not character streams.
    034 * </p>
    035 * <p>
    036 * This class is thread-safe.
    037 * </p>
    038 *
    039 * @see <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>
    040 *
    041 * @since 1.5
    042 * @version $Id: Base32.java 1619949 2014-08-22 22:56:08Z ggregory $
    043 */
    044public class Base32 extends BaseNCodec {
    045
    046    /**
    047     * BASE32 characters are 5 bits in length.
    048     * They are formed by taking a block of five octets to form a 40-bit string,
    049     * which is converted into eight BASE32 characters.
    050     */
    051    private static final int BITS_PER_ENCODED_BYTE = 5;
    052    private static final int BYTES_PER_ENCODED_BLOCK = 8;
    053    private static final int BYTES_PER_UNENCODED_BLOCK = 5;
    054
    055    /**
    056     * Chunk separator per RFC 2045 section 2.1.
    057     *
    058     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
    059     */
    060    private static final byte[] CHUNK_SEPARATOR = {'\r', '\n'};
    061
    062    /**
    063     * This array is a lookup table that translates Unicode characters drawn from the "Base32 Alphabet" (as specified
    064     * in Table 3 of RFC 4648) into their 5-bit positive integer equivalents. Characters that are not in the Base32
    065     * alphabet but fall within the bounds of the array are translated to -1.
    066     */
    067    private static final byte[] DECODE_TABLE = {
    068         //  0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
    069            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
    070            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
    071            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20-2f
    072            -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
    073            -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, // 40-4f A-N
    074            15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,                     // 50-5a O-Z
    075    };
    076
    077    /**
    078     * This array is a lookup table that translates 5-bit positive integer index values into their "Base32 Alphabet"
    079     * equivalents as specified in Table 3 of RFC 4648.
    080     */
    081    private static final byte[] ENCODE_TABLE = {
    082            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    083            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    084            '2', '3', '4', '5', '6', '7',
    085    };
    086
    087    /**
    088     * This array is a lookup table that translates Unicode characters drawn from the "Base32 |Hex Alphabet" (as
    089     * specified in Table 3 of RFC 4648) into their 5-bit positive integer equivalents. Characters that are not in the
    090     * Base32 Hex alphabet but fall within the bounds of the array are translated to -1.
    091     */
    092    private static final byte[] HEX_DECODE_TABLE = {
    093         //  0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
    094            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
    095            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
    096            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20-2f
    097             0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
    098            -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 40-4f A-N
    099            25, 26, 27, 28, 29, 30, 31, 32,                                 // 50-57 O-V
    100    };
    101
    102    /**
    103     * This array is a lookup table that translates 5-bit positive integer index values into their
    104     * "Base32 Hex Alphabet" equivalents as specified in Table 3 of RFC 4648.
    105     */
    106    private static final byte[] HEX_ENCODE_TABLE = {
    107            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    108            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    109            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
    110    };
    111
    112    /** Mask used to extract 5 bits, used when encoding Base32 bytes */
    113    private static final int MASK_5BITS = 0x1f;
    114
    115    // The static final fields above are used for the original static byte[] methods on Base32.
    116    // The private member fields below are used with the new streaming approach, which requires
    117    // some state be preserved between calls of encode() and decode().
    118
    119    /**
    120     * Place holder for the bytes we're dealing with for our based logic.
    121     * Bitwise operations store and extract the encoding or decoding from this variable.
    122     */
    123
    124    /**
    125     * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
    126     * <code>decodeSize = {@link #BYTES_PER_ENCODED_BLOCK} - 1 + lineSeparator.length;</code>
    127     */
    128    private final int decodeSize;
    129
    130    /**
    131     * Decode table to use.
    132     */
    133    private final byte[] decodeTable;
    134
    135    /**
    136     * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
    137     * <code>encodeSize = {@link #BYTES_PER_ENCODED_BLOCK} + lineSeparator.length;</code>
    138     */
    139    private final int encodeSize;
    140
    141    /**
    142     * Encode table to use.
    143     */
    144    private final byte[] encodeTable;
    145
    146    /**
    147     * Line separator for encoding. Not used when decoding. Only used if lineLength &gt; 0.
    148     */
    149    private final byte[] lineSeparator;
    150
    151    /**
    152     * Creates a Base32 codec used for decoding and encoding.
    153     * <p>
    154     * When encoding the line length is 0 (no chunking).
    155     * </p>
    156     *
    157     */
    158    public Base32() {
    159        this(false);
    160    }
    161
    162    /**
    163     * Creates a Base32 codec used for decoding and encoding.
    164     * <p>
    165     * When encoding the line length is 0 (no chunking).
    166     * </p>
    167     * @param pad byte used as padding byte.
    168     */
    169    public Base32(final byte pad) {
    170        this(false, pad);
    171    }
    172
    173    /**
    174     * Creates a Base32 codec used for decoding and encoding.
    175     * <p>
    176     * When encoding the line length is 0 (no chunking).
    177     * </p>
    178     * @param useHex if {@code true} then use Base32 Hex alphabet
    179     */
    180    public Base32(final boolean useHex) {
    181        this(0, null, useHex, PAD_DEFAULT);
    182    }
    183
    184    /**
    185     * Creates a Base32 codec used for decoding and encoding.
    186     * <p>
    187     * When encoding the line length is 0 (no chunking).
    188     * </p>
    189     * @param useHex if {@code true} then use Base32 Hex alphabet
    190     * @param pad byte used as padding byte.
    191     */
    192    public Base32(final boolean useHex, final byte pad) {
    193        this(0, null, useHex, pad);
    194    }
    195
    196    /**
    197     * Creates a Base32 codec used for decoding and encoding.
    198     * <p>
    199     * When encoding the line length is given in the constructor, the line separator is CRLF.
    200     * </p>
    201     *
    202     * @param lineLength
    203     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
    204     *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
    205     *            decoding.
    206     */
    207    public Base32(final int lineLength) {
    208        this(lineLength, CHUNK_SEPARATOR);
    209    }
    210
    211    /**
    212     * Creates a Base32 codec used for decoding and encoding.
    213     * <p>
    214     * When encoding the line length and line separator are given in the constructor.
    215     * </p>
    216     * <p>
    217     * Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
    218     * </p>
    219     *
    220     * @param lineLength
    221     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
    222     *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
    223     *            decoding.
    224     * @param lineSeparator
    225     *            Each line of encoded data will end with this sequence of bytes.
    226     * @throws IllegalArgumentException
    227     *             The provided lineSeparator included some Base32 characters. That's not going to work!
    228     */
    229    public Base32(final int lineLength, final byte[] lineSeparator) {
    230        this(lineLength, lineSeparator, false, PAD_DEFAULT);
    231    }
    232
    233    /**
    234     * Creates a Base32 / Base32 Hex codec used for decoding and encoding.
    235     * <p>
    236     * When encoding the line length and line separator are given in the constructor.
    237     * </p>
    238     * <p>
    239     * Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
    240     * </p>
    241     *
    242     * @param lineLength
    243     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
    244     *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
    245     *            decoding.
    246     * @param lineSeparator
    247     *            Each line of encoded data will end with this sequence of bytes.
    248     * @param useHex
    249     *            if {@code true}, then use Base32 Hex alphabet, otherwise use Base32 alphabet
    250     * @throws IllegalArgumentException
    251     *             The provided lineSeparator included some Base32 characters. That's not going to work! Or the
    252     *             lineLength &gt; 0 and lineSeparator is null.
    253     */
    254    public Base32(final int lineLength, final byte[] lineSeparator, final boolean useHex) {
    255        this(lineLength, lineSeparator, useHex, PAD_DEFAULT);
    256    }
    257
    258    /**
    259     * Creates a Base32 / Base32 Hex codec used for decoding and encoding.
    260     * <p>
    261     * When encoding the line length and line separator are given in the constructor.
    262     * </p>
    263     * <p>
    264     * Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
    265     * </p>
    266     *
    267     * @param lineLength
    268     *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
    269     *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
    270     *            decoding.
    271     * @param lineSeparator
    272     *            Each line of encoded data will end with this sequence of bytes.
    273     * @param useHex
    274     *            if {@code true}, then use Base32 Hex alphabet, otherwise use Base32 alphabet
    275     * @param pad byte used as padding byte.
    276     * @throws IllegalArgumentException
    277     *             The provided lineSeparator included some Base32 characters. That's not going to work! Or the
    278     *             lineLength &gt; 0 and lineSeparator is null.
    279     */
    280    public Base32(final int lineLength, final byte[] lineSeparator, final boolean useHex, final byte pad) {
    281        super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, lineLength,
    282                lineSeparator == null ? 0 : lineSeparator.length, pad);
    283        if (useHex) {
    284            this.encodeTable = HEX_ENCODE_TABLE;
    285            this.decodeTable = HEX_DECODE_TABLE;
    286        } else {
    287            this.encodeTable = ENCODE_TABLE;
    288            this.decodeTable = DECODE_TABLE;
    289        }
    290        if (lineLength > 0) {
    291            if (lineSeparator == null) {
    292                throw new IllegalArgumentException("lineLength " + lineLength + " > 0, but lineSeparator is null");
    293            }
    294            // Must be done after initializing the tables
    295            if (containsAlphabetOrPad(lineSeparator)) {
    296                final String sep = StringUtils.newStringUtf8(lineSeparator);
    297                throw new IllegalArgumentException("lineSeparator must not contain Base32 characters: [" + sep + "]");
    298            }
    299            this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
    300            this.lineSeparator = new byte[lineSeparator.length];
    301            System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
    302        } else {
    303            this.encodeSize = BYTES_PER_ENCODED_BLOCK;
    304            this.lineSeparator = null;
    305        }
    306        this.decodeSize = this.encodeSize - 1;
    307
    308        if (isInAlphabet(pad) || isWhiteSpace(pad)) {
    309            throw new IllegalArgumentException("pad must not be in alphabet or whitespace");
    310        }
    311    }
    312
    313    /**
    314     * <p>
    315     * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
    316     * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
    317     * call is not necessary when decoding, but it doesn't hurt, either.
    318     * </p>
    319     * <p>
    320     * Ignores all non-Base32 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
    321     * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
    322     * garbage-out philosophy: it will not check the provided data for validity.
    323     * </p>
    324     *
    325     * @param in
    326     *            byte[] array of ascii data to Base32 decode.
    327     * @param inPos
    328     *            Position to start reading data from.
    329     * @param inAvail
    330     *            Amount of bytes available from input for encoding.
    331     * @param context the context to be used
    332     *
    333     * Output is written to {@link Context#buffer} as 8-bit octets, using {@link Context#pos} as the buffer position
    334     */
    335    @Override
    336    void decode(final byte[] in, int inPos, final int inAvail, final Context context) {
    337        // package protected for access from I/O streams
    338
    339        if (context.eof) {
    340            return;
    341        }
    342        if (inAvail < 0) {
    343            context.eof = true;
    344        }
    345        for (int i = 0; i < inAvail; i++) {
    346            final byte b = in[inPos++];
    347            if (b == pad) {
    348                // We're done.
    349                context.eof = true;
    350                break;
    351            } else {
    352                final byte[] buffer = ensureBufferSize(decodeSize, context);
    353                if (b >= 0 && b < this.decodeTable.length) {
    354                    final int result = this.decodeTable[b];
    355                    if (result >= 0) {
    356                        context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK;
    357                        // collect decoded bytes
    358                        context.lbitWorkArea = (context.lbitWorkArea << BITS_PER_ENCODED_BYTE) + result;
    359                        if (context.modulus == 0) { // we can output the 5 bytes
    360                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 32) & MASK_8BITS);
    361                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 24) & MASK_8BITS);
    362                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
    363                            buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
    364                            buffer[context.pos++] = (byte) (context.lbitWorkArea & MASK_8BITS);
    365                        }
    366                    }
    367                }
    368            }
    369        }
    370
    371        // Two forms of EOF as far as Base32 decoder is concerned: actual
    372        // EOF (-1) and first time '=' character is encountered in stream.
    373        // This approach makes the '=' padding characters completely optional.
    374        if (context.eof && context.modulus >= 2) { // if modulus < 2, nothing to do
    375            final byte[] buffer = ensureBufferSize(decodeSize, context);
    376
    377            //  we ignore partial bytes, i.e. only multiples of 8 count
    378            switch (context.modulus) {
    379                case 2 : // 10 bits, drop 2 and output one byte
    380                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 2) & MASK_8BITS);
    381                    break;
    382                case 3 : // 15 bits, drop 7 and output 1 byte
    383                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 7) & MASK_8BITS);
    384                    break;
    385                case 4 : // 20 bits = 2*8 + 4
    386                    context.lbitWorkArea = context.lbitWorkArea >> 4; // drop 4 bits
    387                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
    388                    buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
    389                    break;
    390                case 5 : // 25bits = 3*8 + 1
    391                    context.lbitWorkArea = context.lbitWorkArea >> 1;
    392                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
    393                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
    394                    buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
    395                    break;
    396                case 6 : // 30bits = 3*8 + 6
    397                    context.lbitWorkArea = context.lbitWorkArea >> 6;
    398                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
    399                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
    400                    buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
    401                    break;
    402                case 7 : // 35 = 4*8 +3
    403                    context.lbitWorkArea = context.lbitWorkArea >> 3;
    404                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 24) & MASK_8BITS);
    405                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
    406                    buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
    407                    buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
    408                    break;
    409                default:
    410                    // modulus can be 0-7, and we excluded 0,1 already
    411                    throw new IllegalStateException("Impossible modulus "+context.modulus);
    412            }
    413        }
    414    }
    415
    416    /**
    417     * <p>
    418     * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
    419     * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush last
    420     * remaining bytes (if not multiple of 5).
    421     * </p>
    422     *
    423     * @param in
    424     *            byte[] array of binary data to Base32 encode.
    425     * @param inPos
    426     *            Position to start reading data from.
    427     * @param inAvail
    428     *            Amount of bytes available from input for encoding.
    429     * @param context the context to be used
    430     */
    431    @Override
    432    void encode(final byte[] in, int inPos, final int inAvail, final Context context) {
    433        // package protected for access from I/O streams
    434
    435        if (context.eof) {
    436            return;
    437        }
    438        // inAvail < 0 is how we're informed of EOF in the underlying data we're
    439        // encoding.
    440        if (inAvail < 0) {
    441            context.eof = true;
    442            if (0 == context.modulus && lineLength == 0) {
    443                return; // no leftovers to process and not using chunking
    444            }
    445            final byte[] buffer = ensureBufferSize(encodeSize, context);
    446            final int savedPos = context.pos;
    447            switch (context.modulus) { // % 5
    448                case 0 :
    449                    break;
    450                case 1 : // Only 1 octet; take top 5 bits then remainder
    451                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 3) & MASK_5BITS]; // 8-1*5 = 3
    452                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea << 2) & MASK_5BITS]; // 5-3=2
    453                    buffer[context.pos++] = pad;
    454                    buffer[context.pos++] = pad;
    455                    buffer[context.pos++] = pad;
    456                    buffer[context.pos++] = pad;
    457                    buffer[context.pos++] = pad;
    458                    buffer[context.pos++] = pad;
    459                    break;
    460                case 2 : // 2 octets = 16 bits to use
    461                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 11) & MASK_5BITS]; // 16-1*5 = 11
    462                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  6) & MASK_5BITS]; // 16-2*5 = 6
    463                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  1) & MASK_5BITS]; // 16-3*5 = 1
    464                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea <<  4) & MASK_5BITS]; // 5-1 = 4
    465                    buffer[context.pos++] = pad;
    466                    buffer[context.pos++] = pad;
    467                    buffer[context.pos++] = pad;
    468                    buffer[context.pos++] = pad;
    469                    break;
    470                case 3 : // 3 octets = 24 bits to use
    471                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 19) & MASK_5BITS]; // 24-1*5 = 19
    472                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 14) & MASK_5BITS]; // 24-2*5 = 14
    473                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  9) & MASK_5BITS]; // 24-3*5 = 9
    474                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  4) & MASK_5BITS]; // 24-4*5 = 4
    475                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea <<  1) & MASK_5BITS]; // 5-4 = 1
    476                    buffer[context.pos++] = pad;
    477                    buffer[context.pos++] = pad;
    478                    buffer[context.pos++] = pad;
    479                    break;
    480                case 4 : // 4 octets = 32 bits to use
    481                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 27) & MASK_5BITS]; // 32-1*5 = 27
    482                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 22) & MASK_5BITS]; // 32-2*5 = 22
    483                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 17) & MASK_5BITS]; // 32-3*5 = 17
    484                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 12) & MASK_5BITS]; // 32-4*5 = 12
    485                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  7) & MASK_5BITS]; // 32-5*5 =  7
    486                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  2) & MASK_5BITS]; // 32-6*5 =  2
    487                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea <<  3) & MASK_5BITS]; // 5-2 = 3
    488                    buffer[context.pos++] = pad;
    489                    break;
    490                default:
    491                    throw new IllegalStateException("Impossible modulus "+context.modulus);
    492            }
    493            context.currentLinePos += context.pos - savedPos; // keep track of current line position
    494            // if currentPos == 0 we are at the start of a line, so don't add CRLF
    495            if (lineLength > 0 && context.currentLinePos > 0){ // add chunk separator if required
    496                System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
    497                context.pos += lineSeparator.length;
    498            }
    499        } else {
    500            for (int i = 0; i < inAvail; i++) {
    501                final byte[] buffer = ensureBufferSize(encodeSize, context);
    502                context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK;
    503                int b = in[inPos++];
    504                if (b < 0) {
    505                    b += 256;
    506                }
    507                context.lbitWorkArea = (context.lbitWorkArea << 8) + b; // BITS_PER_BYTE
    508                if (0 == context.modulus) { // we have enough bytes to create our output
    509                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 35) & MASK_5BITS];
    510                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 30) & MASK_5BITS];
    511                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 25) & MASK_5BITS];
    512                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 20) & MASK_5BITS];
    513                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 15) & MASK_5BITS];
    514                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 10) & MASK_5BITS];
    515                    buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 5) & MASK_5BITS];
    516                    buffer[context.pos++] = encodeTable[(int)context.lbitWorkArea & MASK_5BITS];
    517                    context.currentLinePos += BYTES_PER_ENCODED_BLOCK;
    518                    if (lineLength > 0 && lineLength <= context.currentLinePos) {
    519                        System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
    520                        context.pos += lineSeparator.length;
    521                        context.currentLinePos = 0;
    522                    }
    523                }
    524            }
    525        }
    526    }
    527
    528    /**
    529     * Returns whether or not the {@code octet} is in the Base32 alphabet.
    530     *
    531     * @param octet
    532     *            The value to test
    533     * @return {@code true} if the value is defined in the the Base32 alphabet {@code false} otherwise.
    534     */
    535    @Override
    536    public boolean isInAlphabet(final byte octet) {
    537        return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
    538    }
    539}