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   *    http://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  package org.apache.directory.api.util;
21  
22  
23  import javax.naming.InvalidNameException;
24  
25  import org.apache.directory.api.i18n.I18n;
26  
27  
28  /**
29   * Various hex and string manipulation methods that are more efficient then
30   * chaining operations: all is done in the same buffer without creating a bunch
31   * of intermediate String objects.
32   *
33   * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
34   */
35  public class Hex
36  {
37      /** &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */
38      public static final byte[] HEX_VALUE =
39          {
40              -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00 -> 0F
41              -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10 -> 1F
42              -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20 -> 2F
43               0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1, // 30 -> 3F ( 0, 1,2, 3, 4,5, 6, 7, 8, 9 )
44              -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 40 -> 4F ( A, B, C, D, E, F )
45              -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 50 -> 5F
46              -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 60 -> 6F ( a, b, c, d, e, f )
47              -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1  // 70 -> 7F
48          };
49  
50      /** Used to build output as Hex */
51      public static final char[] HEX_CHAR =
52          { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
53  
54  
55      /**
56       * Translate two chars to an hex value. The chars must be
57       * in [a-fA-F0-9]
58       *
59       * @param high The high value
60       * @param low The low value
61       * @return A byte representation of the two chars
62       */
63      public static byte getHexValue( char high, char low )
64      {
65          if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) )
66          {
67              return -1;
68          }
69  
70          return ( byte ) ( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
71      }
72  
73  
74      /**
75       * Translate two bytes to an hex value. The bytes must be
76       * in [0-9a-fA-F]
77       *
78       * @param high The high value
79       * @param low The low value
80       * @return A byte representation of the two bytes
81       */
82      public static byte getHexValue( byte high, byte low )
83      {
84          if ( ( ( high & 0x7F ) != high ) || ( ( low & 0x7F ) != low ) )
85          {
86              return -1;
87          }
88  
89          return ( byte ) ( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
90      }
91  
92  
93      /**
94       * Return an hex value from a single char
95       * The char must be in [0-9a-fA-F]
96       *
97       * @param c The char we want to convert
98       * @return A byte between 0 and 15
99       */
100     public static byte getHexValue( char c )
101     {
102         if ( ( c > 127 ) || ( c < 0 ) )
103         {
104             return -1;
105         }
106 
107         return HEX_VALUE[c];
108     }
109 
110 
111     /**
112      * Decodes values of attributes in the DN encoded in hex into a UTF-8
113      * String.  RFC2253 allows a DN's attribute to be encoded in hex.
114      * The encoded value starts with a # then is followed by an even
115      * number of hex characters.
116      *
117      * @param str the string to decode
118      * @return the decoded string
119      * @throws InvalidNameException
120      */
121     public static String decodeHexString( String str ) throws InvalidNameException
122     {
123         if ( str == null || str.length() == 0 )
124         {
125             throw new InvalidNameException( I18n.err( I18n.ERR_04431 ) );
126         }
127 
128         char[] chars = str.toCharArray();
129 
130         if ( chars[0] != '#' )
131         {
132             throw new InvalidNameException( I18n.err( I18n.ERR_04432, str ) );
133         }
134 
135         // the bytes representing the encoded string of hex
136         // this should be ( length - 1 )/2 in size
137         byte[] decoded = new byte[( chars.length - 1 ) >> 1];
138 
139         for ( int ii = 1, jj = 0; ii < chars.length; ii += 2, jj++ )
140         {
141             int ch = ( HEX_VALUE[chars[ii]] << 4 )
142                 + HEX_VALUE[chars[ii + 1]];
143             decoded[jj] = ( byte ) ch;
144         }
145 
146         return Strings.utf8ToString( decoded );
147     }
148 
149 
150     /**
151      * Convert an escaoed list of bytes to a byte[]
152      *
153      * @param str the string containing hex escapes
154      * @return the converted byte[]
155      */
156     public static byte[] convertEscapedHex( String str ) throws InvalidNameException
157     {
158         if ( str == null )
159         {
160             throw new InvalidNameException( I18n.err( I18n.ERR_04433 ) );
161         }
162 
163         int length = str.length();
164 
165         if ( length == 0 )
166         {
167             throw new InvalidNameException( I18n.err( I18n.ERR_04434 ) );
168         }
169 
170         // create buffer and add everything before start of scan
171         byte[] buf = new byte[str.length() / 3];
172         int pos = 0;
173 
174         // start scaning until we find an escaped series of bytes
175         for ( int i = 0; i < length; i++ )
176         {
177             char c = str.charAt( i );
178 
179             if ( c == '\\' )
180             {
181                 // we have the start of a hex escape sequence
182                 if ( Chars.isHex( str, i + 1 ) && Chars.isHex( str, i + 2 ) )
183                 {
184                     byte value = ( byte ) ( ( HEX_VALUE[str.charAt( i + 1 )] << 4 )
185                         + HEX_VALUE[str.charAt( i + 2 )] );
186 
187                     i += 2;
188                     buf[pos++] = value;
189                 }
190             }
191             else
192             {
193                 throw new InvalidNameException( I18n.err( I18n.ERR_04435 ) );
194             }
195         }
196 
197         return buf;
198     }
199 
200 
201     /**
202      * Converts an array of bytes into an array of characters representing the
203      * hexadecimal values of each byte in order. The returned array will be
204      * double the length of the passed array, as it takes two characters to
205      * represent any given byte.
206      *
207      * @param data a byte[] to convert to Hex characters
208      * @return A char[] containing hexadecimal characters
209      */
210     public static char[] encodeHex( byte[] data )
211     {
212         int l = data.length;
213 
214         char[] out = new char[l << 1];
215 
216         // two characters form the hex value.
217         for ( int i = 0, j = 0; i < l; i++ )
218         {
219             out[j++] = HEX_CHAR[( 0xF0 & data[i] ) >>> 4];
220             out[j++] = HEX_CHAR[0x0F & data[i]];
221         }
222 
223         return out;
224     }
225 }