Base32.java

  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. package org.apache.commons.codec.binary;

  18. /**
  19.  * Provides Base32 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>.
  20.  *
  21.  * <p>
  22.  * The class can be parameterized in the following manner with various constructors:
  23.  * </p>
  24.  * <ul>
  25.  * <li>Whether to use the "base32hex" variant instead of the default "base32"</li>
  26.  * <li>Line length: Default 76. Line length that aren't multiples of 8 will still essentially end up being multiples of
  27.  * 8 in the encoded data.
  28.  * <li>Line separator: Default is CRLF ("\r\n")</li>
  29.  * </ul>
  30.  * <p>
  31.  * This class operates directly on byte streams, and not character streams.
  32.  * </p>
  33.  * <p>
  34.  * This class is thread-safe.
  35.  * </p>
  36.  *
  37.  * @see <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>
  38.  *
  39.  * @since 1.5
  40.  * @version $Id: Base32.java 1809441 2017-09-23 16:41:53Z ggregory $
  41.  */
  42. public class Base32 extends BaseNCodec {

  43.     /**
  44.      * BASE32 characters are 5 bits in length.
  45.      * They are formed by taking a block of five octets to form a 40-bit string,
  46.      * which is converted into eight BASE32 characters.
  47.      */
  48.     private static final int BITS_PER_ENCODED_BYTE = 5;
  49.     private static final int BYTES_PER_ENCODED_BLOCK = 8;
  50.     private static final int BYTES_PER_UNENCODED_BLOCK = 5;

  51.     /**
  52.      * Chunk separator per RFC 2045 section 2.1.
  53.      *
  54.      * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
  55.      */
  56.     private static final byte[] CHUNK_SEPARATOR = {'\r', '\n'};

  57.     /**
  58.      * This array is a lookup table that translates Unicode characters drawn from the "Base32 Alphabet" (as specified
  59.      * in Table 3 of RFC 4648) into their 5-bit positive integer equivalents. Characters that are not in the Base32
  60.      * alphabet but fall within the bounds of the array are translated to -1.
  61.      */
  62.     private static final byte[] DECODE_TABLE = {
  63.          //  0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
  64.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
  65.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
  66.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20-2f
  67.             -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
  68.             -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, // 40-4f A-O
  69.             15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,                     // 50-5a P-Z
  70.                                                         -1, -1, -1, -1, -1, // 5b - 5f
  71.             -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, // 60 - 6f a-o
  72.             15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,                     // 70 - 7a p-z/**/
  73.     };

  74.     /**
  75.      * This array is a lookup table that translates 5-bit positive integer index values into their "Base32 Alphabet"
  76.      * equivalents as specified in Table 3 of RFC 4648.
  77.      */
  78.     private static final byte[] ENCODE_TABLE = {
  79.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  80.             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  81.             '2', '3', '4', '5', '6', '7',
  82.     };

  83.     /**
  84.      * This array is a lookup table that translates Unicode characters drawn from the "Base32 Hex Alphabet" (as
  85.      * specified in Table 4 of RFC 4648) into their 5-bit positive integer equivalents. Characters that are not in the
  86.      * Base32 Hex alphabet but fall within the bounds of the array are translated to -1.
  87.      */
  88.     private static final byte[] HEX_DECODE_TABLE = {
  89.          //  0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
  90.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
  91.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
  92.             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20-2f
  93.              0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1, // 30-3f 2-7
  94.             -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 40-4f A-O
  95.             25, 26, 27, 28, 29, 30, 31,                                     // 50-56 P-V
  96.                                         -1, -1, -1, -1, -1, -1, -1, -1, -1, // 57-5f Z-_
  97.             -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 60-6f `-o
  98.             25, 26, 27, 28, 29, 30, 31                                      // 70-76 p-v
  99.     };

  100.     /**
  101.      * This array is a lookup table that translates 5-bit positive integer index values into their
  102.      * "Base32 Hex Alphabet" equivalents as specified in Table 4 of RFC 4648.
  103.      */
  104.     private static final byte[] HEX_ENCODE_TABLE = {
  105.             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  106.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  107.             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
  108.     };

  109.     /** Mask used to extract 5 bits, used when encoding Base32 bytes */
  110.     private static final int MASK_5BITS = 0x1f;

  111.     // The static final fields above are used for the original static byte[] methods on Base32.
  112.     // The private member fields below are used with the new streaming approach, which requires
  113.     // some state be preserved between calls of encode() and decode().

  114.     /**
  115.      * Place holder for the bytes we're dealing with for our based logic.
  116.      * Bitwise operations store and extract the encoding or decoding from this variable.
  117.      */

  118.     /**
  119.      * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
  120.      * <code>decodeSize = {@link #BYTES_PER_ENCODED_BLOCK} - 1 + lineSeparator.length;</code>
  121.      */
  122.     private final int decodeSize;

  123.     /**
  124.      * Decode table to use.
  125.      */
  126.     private final byte[] decodeTable;

  127.     /**
  128.      * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.
  129.      * <code>encodeSize = {@link #BYTES_PER_ENCODED_BLOCK} + lineSeparator.length;</code>
  130.      */
  131.     private final int encodeSize;

  132.     /**
  133.      * Encode table to use.
  134.      */
  135.     private final byte[] encodeTable;

  136.     /**
  137.      * Line separator for encoding. Not used when decoding. Only used if lineLength &gt; 0.
  138.      */
  139.     private final byte[] lineSeparator;

  140.     /**
  141.      * Creates a Base32 codec used for decoding and encoding.
  142.      * <p>
  143.      * When encoding the line length is 0 (no chunking).
  144.      * </p>
  145.      *
  146.      */
  147.     public Base32() {
  148.         this(false);
  149.     }

  150.     /**
  151.      * Creates a Base32 codec used for decoding and encoding.
  152.      * <p>
  153.      * When encoding the line length is 0 (no chunking).
  154.      * </p>
  155.      * @param pad byte used as padding byte.
  156.      */
  157.     public Base32(final byte pad) {
  158.         this(false, pad);
  159.     }

  160.     /**
  161.      * Creates a Base32 codec used for decoding and encoding.
  162.      * <p>
  163.      * When encoding the line length is 0 (no chunking).
  164.      * </p>
  165.      * @param useHex if {@code true} then use Base32 Hex alphabet
  166.      */
  167.     public Base32(final boolean useHex) {
  168.         this(0, null, useHex, PAD_DEFAULT);
  169.     }

  170.     /**
  171.      * Creates a Base32 codec used for decoding and encoding.
  172.      * <p>
  173.      * When encoding the line length is 0 (no chunking).
  174.      * </p>
  175.      * @param useHex if {@code true} then use Base32 Hex alphabet
  176.      * @param pad byte used as padding byte.
  177.      */
  178.     public Base32(final boolean useHex, final byte pad) {
  179.         this(0, null, useHex, pad);
  180.     }

  181.     /**
  182.      * Creates a Base32 codec used for decoding and encoding.
  183.      * <p>
  184.      * When encoding the line length is given in the constructor, the line separator is CRLF.
  185.      * </p>
  186.      *
  187.      * @param lineLength
  188.      *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
  189.      *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
  190.      *            decoding.
  191.      */
  192.     public Base32(final int lineLength) {
  193.         this(lineLength, CHUNK_SEPARATOR);
  194.     }

  195.     /**
  196.      * Creates a Base32 codec used for decoding and encoding.
  197.      * <p>
  198.      * When encoding the line length and line separator are given in the constructor.
  199.      * </p>
  200.      * <p>
  201.      * Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
  202.      * </p>
  203.      *
  204.      * @param lineLength
  205.      *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
  206.      *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
  207.      *            decoding.
  208.      * @param lineSeparator
  209.      *            Each line of encoded data will end with this sequence of bytes.
  210.      * @throws IllegalArgumentException
  211.      *             The provided lineSeparator included some Base32 characters. That's not going to work!
  212.      */
  213.     public Base32(final int lineLength, final byte[] lineSeparator) {
  214.         this(lineLength, lineSeparator, false, PAD_DEFAULT);
  215.     }

  216.     /**
  217.      * Creates a Base32 / Base32 Hex codec used for decoding and encoding.
  218.      * <p>
  219.      * When encoding the line length and line separator are given in the constructor.
  220.      * </p>
  221.      * <p>
  222.      * Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
  223.      * </p>
  224.      *
  225.      * @param lineLength
  226.      *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
  227.      *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
  228.      *            decoding.
  229.      * @param lineSeparator
  230.      *            Each line of encoded data will end with this sequence of bytes.
  231.      * @param useHex
  232.      *            if {@code true}, then use Base32 Hex alphabet, otherwise use Base32 alphabet
  233.      * @throws IllegalArgumentException
  234.      *             The provided lineSeparator included some Base32 characters. That's not going to work! Or the
  235.      *             lineLength &gt; 0 and lineSeparator is null.
  236.      */
  237.     public Base32(final int lineLength, final byte[] lineSeparator, final boolean useHex) {
  238.         this(lineLength, lineSeparator, useHex, PAD_DEFAULT);
  239.     }

  240.     /**
  241.      * Creates a Base32 / Base32 Hex codec used for decoding and encoding.
  242.      * <p>
  243.      * When encoding the line length and line separator are given in the constructor.
  244.      * </p>
  245.      * <p>
  246.      * Line lengths that aren't multiples of 8 will still essentially end up being multiples of 8 in the encoded data.
  247.      * </p>
  248.      *
  249.      * @param lineLength
  250.      *            Each line of encoded data will be at most of the given length (rounded down to nearest multiple of
  251.      *            8). If lineLength &lt;= 0, then the output will not be divided into lines (chunks). Ignored when
  252.      *            decoding.
  253.      * @param lineSeparator
  254.      *            Each line of encoded data will end with this sequence of bytes.
  255.      * @param useHex
  256.      *            if {@code true}, then use Base32 Hex alphabet, otherwise use Base32 alphabet
  257.      * @param pad byte used as padding byte.
  258.      * @throws IllegalArgumentException
  259.      *             The provided lineSeparator included some Base32 characters. That's not going to work! Or the
  260.      *             lineLength &gt; 0 and lineSeparator is null.
  261.      */
  262.     public Base32(final int lineLength, final byte[] lineSeparator, final boolean useHex, final byte pad) {
  263.         super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, lineLength,
  264.                 lineSeparator == null ? 0 : lineSeparator.length, pad);
  265.         if (useHex) {
  266.             this.encodeTable = HEX_ENCODE_TABLE;
  267.             this.decodeTable = HEX_DECODE_TABLE;
  268.         } else {
  269.             this.encodeTable = ENCODE_TABLE;
  270.             this.decodeTable = DECODE_TABLE;
  271.         }
  272.         if (lineLength > 0) {
  273.             if (lineSeparator == null) {
  274.                 throw new IllegalArgumentException("lineLength " + lineLength + " > 0, but lineSeparator is null");
  275.             }
  276.             // Must be done after initializing the tables
  277.             if (containsAlphabetOrPad(lineSeparator)) {
  278.                 final String sep = StringUtils.newStringUtf8(lineSeparator);
  279.                 throw new IllegalArgumentException("lineSeparator must not contain Base32 characters: [" + sep + "]");
  280.             }
  281.             this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
  282.             this.lineSeparator = new byte[lineSeparator.length];
  283.             System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
  284.         } else {
  285.             this.encodeSize = BYTES_PER_ENCODED_BLOCK;
  286.             this.lineSeparator = null;
  287.         }
  288.         this.decodeSize = this.encodeSize - 1;

  289.         if (isInAlphabet(pad) || isWhiteSpace(pad)) {
  290.             throw new IllegalArgumentException("pad must not be in alphabet or whitespace");
  291.         }
  292.     }

  293.     /**
  294.      * <p>
  295.      * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
  296.      * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
  297.      * call is not necessary when decoding, but it doesn't hurt, either.
  298.      * </p>
  299.      * <p>
  300.      * Ignores all non-Base32 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
  301.      * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
  302.      * garbage-out philosophy: it will not check the provided data for validity.
  303.      * </p>
  304.      *
  305.      * @param in
  306.      *            byte[] array of ascii data to Base32 decode.
  307.      * @param inPos
  308.      *            Position to start reading data from.
  309.      * @param inAvail
  310.      *            Amount of bytes available from input for encoding.
  311.      * @param context the context to be used
  312.      *
  313.      * Output is written to {@link Context#buffer} as 8-bit octets, using {@link Context#pos} as the buffer position
  314.      */
  315.     @Override
  316.     void decode(final byte[] in, int inPos, final int inAvail, final Context context) {
  317.         // package protected for access from I/O streams

  318.         if (context.eof) {
  319.             return;
  320.         }
  321.         if (inAvail < 0) {
  322.             context.eof = true;
  323.         }
  324.         for (int i = 0; i < inAvail; i++) {
  325.             final byte b = in[inPos++];
  326.             if (b == pad) {
  327.                 // We're done.
  328.                 context.eof = true;
  329.                 break;
  330.             }
  331.             final byte[] buffer = ensureBufferSize(decodeSize, context);
  332.             if (b >= 0 && b < this.decodeTable.length) {
  333.                 final int result = this.decodeTable[b];
  334.                 if (result >= 0) {
  335.                     context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK;
  336.                     // collect decoded bytes
  337.                     context.lbitWorkArea = (context.lbitWorkArea << BITS_PER_ENCODED_BYTE) + result;
  338.                     if (context.modulus == 0) { // we can output the 5 bytes
  339.                         buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 32) & MASK_8BITS);
  340.                         buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 24) & MASK_8BITS);
  341.                         buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
  342.                         buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
  343.                         buffer[context.pos++] = (byte) (context.lbitWorkArea & MASK_8BITS);
  344.                     }
  345.                 }
  346.             }
  347.         }

  348.         // Two forms of EOF as far as Base32 decoder is concerned: actual
  349.         // EOF (-1) and first time '=' character is encountered in stream.
  350.         // This approach makes the '=' padding characters completely optional.
  351.         if (context.eof && context.modulus >= 2) { // if modulus < 2, nothing to do
  352.             final byte[] buffer = ensureBufferSize(decodeSize, context);

  353.             //  we ignore partial bytes, i.e. only multiples of 8 count
  354.             switch (context.modulus) {
  355.                 case 2 : // 10 bits, drop 2 and output one byte
  356.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 2) & MASK_8BITS);
  357.                     break;
  358.                 case 3 : // 15 bits, drop 7 and output 1 byte
  359.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 7) & MASK_8BITS);
  360.                     break;
  361.                 case 4 : // 20 bits = 2*8 + 4
  362.                     context.lbitWorkArea = context.lbitWorkArea >> 4; // drop 4 bits
  363.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
  364.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
  365.                     break;
  366.                 case 5 : // 25bits = 3*8 + 1
  367.                     context.lbitWorkArea = context.lbitWorkArea >> 1;
  368.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
  369.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
  370.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
  371.                     break;
  372.                 case 6 : // 30bits = 3*8 + 6
  373.                     context.lbitWorkArea = context.lbitWorkArea >> 6;
  374.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
  375.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
  376.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
  377.                     break;
  378.                 case 7 : // 35 = 4*8 +3
  379.                     context.lbitWorkArea = context.lbitWorkArea >> 3;
  380.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 24) & MASK_8BITS);
  381.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 16) & MASK_8BITS);
  382.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea >> 8) & MASK_8BITS);
  383.                     buffer[context.pos++] = (byte) ((context.lbitWorkArea) & MASK_8BITS);
  384.                     break;
  385.                 default:
  386.                     // modulus can be 0-7, and we excluded 0,1 already
  387.                     throw new IllegalStateException("Impossible modulus "+context.modulus);
  388.             }
  389.         }
  390.     }

  391.     /**
  392.      * <p>
  393.      * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
  394.      * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush last
  395.      * remaining bytes (if not multiple of 5).
  396.      * </p>
  397.      *
  398.      * @param in
  399.      *            byte[] array of binary data to Base32 encode.
  400.      * @param inPos
  401.      *            Position to start reading data from.
  402.      * @param inAvail
  403.      *            Amount of bytes available from input for encoding.
  404.      * @param context the context to be used
  405.      */
  406.     @Override
  407.     void encode(final byte[] in, int inPos, final int inAvail, final Context context) {
  408.         // package protected for access from I/O streams

  409.         if (context.eof) {
  410.             return;
  411.         }
  412.         // inAvail < 0 is how we're informed of EOF in the underlying data we're
  413.         // encoding.
  414.         if (inAvail < 0) {
  415.             context.eof = true;
  416.             if (0 == context.modulus && lineLength == 0) {
  417.                 return; // no leftovers to process and not using chunking
  418.             }
  419.             final byte[] buffer = ensureBufferSize(encodeSize, context);
  420.             final int savedPos = context.pos;
  421.             switch (context.modulus) { // % 5
  422.                 case 0 :
  423.                     break;
  424.                 case 1 : // Only 1 octet; take top 5 bits then remainder
  425.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 3) & MASK_5BITS]; // 8-1*5 = 3
  426.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea << 2) & MASK_5BITS]; // 5-3=2
  427.                     buffer[context.pos++] = pad;
  428.                     buffer[context.pos++] = pad;
  429.                     buffer[context.pos++] = pad;
  430.                     buffer[context.pos++] = pad;
  431.                     buffer[context.pos++] = pad;
  432.                     buffer[context.pos++] = pad;
  433.                     break;
  434.                 case 2 : // 2 octets = 16 bits to use
  435.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 11) & MASK_5BITS]; // 16-1*5 = 11
  436.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  6) & MASK_5BITS]; // 16-2*5 = 6
  437.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  1) & MASK_5BITS]; // 16-3*5 = 1
  438.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea <<  4) & MASK_5BITS]; // 5-1 = 4
  439.                     buffer[context.pos++] = pad;
  440.                     buffer[context.pos++] = pad;
  441.                     buffer[context.pos++] = pad;
  442.                     buffer[context.pos++] = pad;
  443.                     break;
  444.                 case 3 : // 3 octets = 24 bits to use
  445.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 19) & MASK_5BITS]; // 24-1*5 = 19
  446.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 14) & MASK_5BITS]; // 24-2*5 = 14
  447.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  9) & MASK_5BITS]; // 24-3*5 = 9
  448.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  4) & MASK_5BITS]; // 24-4*5 = 4
  449.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea <<  1) & MASK_5BITS]; // 5-4 = 1
  450.                     buffer[context.pos++] = pad;
  451.                     buffer[context.pos++] = pad;
  452.                     buffer[context.pos++] = pad;
  453.                     break;
  454.                 case 4 : // 4 octets = 32 bits to use
  455.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 27) & MASK_5BITS]; // 32-1*5 = 27
  456.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 22) & MASK_5BITS]; // 32-2*5 = 22
  457.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 17) & MASK_5BITS]; // 32-3*5 = 17
  458.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 12) & MASK_5BITS]; // 32-4*5 = 12
  459.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  7) & MASK_5BITS]; // 32-5*5 =  7
  460.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >>  2) & MASK_5BITS]; // 32-6*5 =  2
  461.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea <<  3) & MASK_5BITS]; // 5-2 = 3
  462.                     buffer[context.pos++] = pad;
  463.                     break;
  464.                 default:
  465.                     throw new IllegalStateException("Impossible modulus "+context.modulus);
  466.             }
  467.             context.currentLinePos += context.pos - savedPos; // keep track of current line position
  468.             // if currentPos == 0 we are at the start of a line, so don't add CRLF
  469.             if (lineLength > 0 && context.currentLinePos > 0){ // add chunk separator if required
  470.                 System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
  471.                 context.pos += lineSeparator.length;
  472.             }
  473.         } else {
  474.             for (int i = 0; i < inAvail; i++) {
  475.                 final byte[] buffer = ensureBufferSize(encodeSize, context);
  476.                 context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK;
  477.                 int b = in[inPos++];
  478.                 if (b < 0) {
  479.                     b += 256;
  480.                 }
  481.                 context.lbitWorkArea = (context.lbitWorkArea << 8) + b; // BITS_PER_BYTE
  482.                 if (0 == context.modulus) { // we have enough bytes to create our output
  483.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 35) & MASK_5BITS];
  484.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 30) & MASK_5BITS];
  485.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 25) & MASK_5BITS];
  486.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 20) & MASK_5BITS];
  487.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 15) & MASK_5BITS];
  488.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 10) & MASK_5BITS];
  489.                     buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 5) & MASK_5BITS];
  490.                     buffer[context.pos++] = encodeTable[(int)context.lbitWorkArea & MASK_5BITS];
  491.                     context.currentLinePos += BYTES_PER_ENCODED_BLOCK;
  492.                     if (lineLength > 0 && lineLength <= context.currentLinePos) {
  493.                         System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
  494.                         context.pos += lineSeparator.length;
  495.                         context.currentLinePos = 0;
  496.                     }
  497.                 }
  498.             }
  499.         }
  500.     }

  501.     /**
  502.      * Returns whether or not the {@code octet} is in the Base32 alphabet.
  503.      *
  504.      * @param octet
  505.      *            The value to test
  506.      * @return {@code true} if the value is defined in the the Base32 alphabet {@code false} otherwise.
  507.      */
  508.     @Override
  509.     public boolean isInAlphabet(final byte octet) {
  510.         return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
  511.     }
  512. }