View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *  
10   *    https://www.apache.org/licenses/LICENSE-2.0
11   *  
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License. 
18   *  
19   */
20  
21  package org.apache.directory.api.util;
22  
23  
24  import org.apache.directory.api.i18n.I18n;
25  
26  
27  /**
28   * Encoding and decoding of Base64 characters to and from raw bytes.
29   * 
30   * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
31   */
32  public final class Base64
33  {
34  
35      /** code characters for values 0..63 */
36      private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
37          .toCharArray();
38  
39      /** lookup table for converting base64 characters to value in range 0..63 */
40      private static final byte[] CODES = new byte[256];
41  
42      static
43      {
44          for ( int ii = 0; ii < 256; ii++ )
45          {
46              CODES[ii] = -1;
47          }
48  
49          for ( int ii = 'A'; ii <= 'Z'; ii++ )
50          {
51              CODES[ii] = ( byte ) ( ii - 'A' );
52          }
53  
54          for ( int ii = 'a'; ii <= 'z'; ii++ )
55          {
56              CODES[ii] = ( byte ) ( 26 + ii - 'a' );
57          }
58  
59          for ( int ii = '0'; ii <= '9'; ii++ )
60          {
61              CODES[ii] = ( byte ) ( 52 + ii - '0' );
62          }
63  
64          CODES['+'] = 62;
65          CODES['/'] = 63;
66      }
67  
68      /**
69       * Private constructor.
70       */
71      private Base64()
72      {
73      }
74  
75  
76      /**
77       * Encodes binary data to a Base64 encoded characters.
78       * 
79       * @param data
80       *            the array of bytes to encode
81       * @return base64-coded character array.
82       * @deprecated Use the java.util.Base64.getEncoder().encode(byte[]) method instead
83       */
84      public static char[] encode( byte[] data )
85      {
86          char[] out = new char[( ( data.length + 2 ) / 3 ) * 4];
87  
88          //
89          // 3 bytes encode to 4 chars. Output is always an even
90          // multiple of 4 characters.
91          //
92          for ( int i = 0, index = 0; i < data.length; i += 3, index += 4 )
93          {
94              boolean isQuadrupel = false;
95              boolean isTripel = false;
96  
97              int val = 0xFF & data[i];
98              val <<= 8;
99              if ( ( i + 1 ) < data.length )
100             {
101                 val |= ( 0xFF & data[i + 1] );
102                 isTripel = true;
103             }
104 
105             val <<= 8;
106             if ( ( i + 2 ) < data.length )
107             {
108                 val |= ( 0xFF & data[i + 2] );
109                 isQuadrupel = true;
110             }
111 
112             out[index + 3] = ALPHABET[ isQuadrupel ? ( val & 0x3F ) : 64 ];
113             val >>= 6;
114             out[index + 2] = ALPHABET[ isTripel ? ( val & 0x3F ) : 64 ];
115             val >>= 6;
116             out[index + 1] = ALPHABET[val & 0x3F];
117             val >>= 6;
118             out[index + 0] = ALPHABET[val & 0x3F];
119         }
120         return out;
121     }
122 
123 
124     /**
125      * Decodes a BASE-64 encoded stream to recover the original data. White
126      * space before and after will be trimmed away, but no other manipulation of
127      * the input will be performed. As of version 1.2 this method will properly
128      * handle input containing junk characters (newlines and the like) rather
129      * than throwing an error. It does this by pre-parsing the input and
130      * generating from that a count of VALID input characters.
131      * 
132      * @param data
133      *            data to decode.
134      * @return the decoded binary data.
135      * @deprecated Use the java.util.Base64.geDecoder().decode(String) method instead
136      */
137     public static byte[] decode( char[] data )
138     {
139         // as our input could contain non-BASE64 data (newlines,
140         // whitespace of any sort, whatever) we must first adjust
141         // our count of USABLE data so that...
142         // (a) we don't misallocate the output array, and
143         // (b) think that we miscalculated our data length
144         // just because of extraneous throw-away junk
145 
146         int tempLen = data.length;
147 
148         for ( char c : data )
149         {
150             if ( ( c > 255 ) || CODES[c] < 0 )
151             {
152                 // ignore non-valid chars and padding
153                 --tempLen;
154             }
155         }
156         // calculate required length:
157         // -- 3 bytes for every 4 valid base64 chars
158         // -- plus 2 bytes if there are 3 extra base64 chars,
159         // or plus 1 byte if there are 2 extra.
160 
161         int len = ( tempLen / 4 ) * 3;
162 
163         if ( ( tempLen % 4 ) == 3 )
164         {
165             len += 2;
166         }
167 
168         if ( ( tempLen % 4 ) == 2 )
169         {
170             len += 1;
171         }
172 
173         byte[] out = new byte[len];
174 
175         // # of excess bits stored in accum excess bits
176         int shift = 0;
177         int accum = 0;
178         int index = 0;
179 
180         // we now go through the entire array (NOT using the 'tempLen' value)
181         for ( char c : data )
182         {
183             int value = ( c > 255 ) ? -1 : CODES[c];
184 
185             // skip over non-code bits 
186             if ( value >= 0 )
187             {
188                 // shift up by 6 each time thru
189                 // loop, with new bits being put in
190                 // at the bottom. whenever there
191                 // are 8 or more shifted in, write them
192                 // out (from the top, leaving any excess
193                 // at the bottom for next iteration.
194                 accum <<= 6;
195                 shift += 6;
196                 accum |= value;
197 
198                 if ( shift >= 8 )
199                 {
200                     shift -= 8;
201                     out[index++] = ( byte ) ( ( accum >> shift ) & 0xff );
202                 }
203             }
204             // we will also have skipped processing a padding null byte ('=') here;
205             // these are used ONLY for padding to an even length and do not legally
206             // occur as encoded data. for this reason we can ignore the fact
207             // that no index++ operation occurs in that special case: the out[] array
208             // is initialized to all-zero bytes to start with and that works to our
209             // advantage in this combination.
210         }
211 
212         // if there is STILL something wrong we just have to throw up now!
213         if ( index != out.length )
214         {
215             throw new Error( I18n.err( I18n.ERR_17027_WRONG_DATA_LENGTH, index, out.length ) );
216         }
217 
218         return out;
219     }
220 }