001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.directory.api.util;
021
022
023import javax.naming.InvalidNameException;
024
025import org.apache.directory.api.i18n.I18n;
026
027
028/**
029 * Various hex and string manipulation methods that are more efficient then
030 * chaining operations: all is done in the same buffer without creating a bunch
031 * of intermediate String objects.
032 *
033 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
034 */
035public final class Hex
036{
037    /** &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */
038    private static final byte[] HEX_VALUE =
039        {
040            // 00 -> 0F
041            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
042            // 10 -> 1F
043            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
044            // 20 -> 2F
045            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
046            // 30 -> 3F ( 0, 1,2, 3, 4,5, 6, 7, 8, 9 )
047             0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1, 
048             // 40 -> 4F ( A, B, C, D, E, F )
049            -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
050            // 50 -> 5F
051            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
052            // 60 -> 6F ( a, b, c, d, e, f )
053            -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
054            // 70 -> 7F
055            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
056    };
057
058    /** Used to build output as Hex */
059    private static final char[] HEX_CHAR =
060        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
061
062
063    private Hex()
064    {
065    }
066
067
068    /**
069     * Translate two chars to an hex value. The chars must be
070     * in [a-fA-F0-9]
071     *
072     * @param high The high value
073     * @param low The low value
074     * @return A byte representation of the two chars
075     */
076    public static byte getHexValue( char high, char low )
077    {
078        if ( ( high > 127 ) || ( low > 127 ) )
079        {
080            return -1;
081        }
082
083        return ( byte ) ( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
084    }
085
086
087    /**
088     * Translate two bytes to an hex value. The bytes must be
089     * in [0-9a-fA-F]
090     *
091     * @param high The high value
092     * @param low The low value
093     * @return A byte representation of the two bytes
094     */
095    public static byte getHexValue( byte high, byte low )
096    {
097        if ( ( ( high & 0x7F ) != high ) || ( ( low & 0x7F ) != low ) )
098        {
099            return -1;
100        }
101
102        return ( byte ) ( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
103    }
104
105
106    /**
107     * Return an hex value from a single char
108     * The char must be in [0-9a-fA-F]
109     *
110     * @param c The char we want to convert
111     * @return A byte between 0 and 15
112     */
113    public static byte getHexValue( char c )
114    {
115        if ( c > 127 )
116        {
117            return -1;
118        }
119
120        return HEX_VALUE[c];
121    }
122
123
124    /**
125     * Decodes values of attributes in the DN encoded in hex into a UTF-8
126     * String.  RFC2253 allows a DN's attribute to be encoded in hex.
127     * The encoded value starts with a # then is followed by an even
128     * number of hex characters.
129     *
130     * @param str the string to decode
131     * @return the decoded string
132     * @throws InvalidNameException
133     */
134    public static String decodeHexString( String str ) throws InvalidNameException
135    {
136        if ( str == null || str.length() == 0 )
137        {
138            throw new InvalidNameException( I18n.err( I18n.ERR_04431 ) );
139        }
140
141        char[] chars = str.toCharArray();
142
143        if ( chars[0] != '#' )
144        {
145            throw new InvalidNameException( I18n.err( I18n.ERR_04432, str ) );
146        }
147
148        // the bytes representing the encoded string of hex
149        // this should be ( length - 1 )/2 in size
150        byte[] decoded = new byte[( chars.length - 1 ) >> 1];
151
152        for ( int ii = 1, jj = 0; ii < chars.length; ii += 2, jj++ )
153        {
154            int ch = ( HEX_VALUE[chars[ii]] << 4 )
155                + HEX_VALUE[chars[ii + 1]];
156            decoded[jj] = ( byte ) ch;
157        }
158
159        return Strings.utf8ToString( decoded );
160    }
161
162
163    /**
164     * Convert an escaoed list of bytes to a byte[]
165     *
166     * @param str the string containing hex escapes
167     * @return the converted byte[]
168     */
169    public static byte[] convertEscapedHex( String str ) throws InvalidNameException
170    {
171        if ( str == null )
172        {
173            throw new InvalidNameException( I18n.err( I18n.ERR_04433 ) );
174        }
175
176        int length = str.length();
177
178        if ( length == 0 )
179        {
180            throw new InvalidNameException( I18n.err( I18n.ERR_04434 ) );
181        }
182
183        // create buffer and add everything before start of scan
184        byte[] buf = new byte[str.length() / 3];
185        int pos = 0;
186
187        // start scaning until we find an escaped series of bytes
188        for ( int i = 0; i < length; i++ )
189        {
190            char c = str.charAt( i );
191
192            if ( c == '\\' )
193            {
194                // we have the start of a hex escape sequence
195                if ( Chars.isHex( str, i + 1 ) && Chars.isHex( str, i + 2 ) )
196                {
197                    byte value = ( byte ) ( ( HEX_VALUE[str.charAt( i + 1 )] << 4 )
198                        + HEX_VALUE[str.charAt( i + 2 )] );
199
200                    i += 2;
201                    buf[pos++] = value;
202                }
203            }
204            else
205            {
206                throw new InvalidNameException( I18n.err( I18n.ERR_04435 ) );
207            }
208        }
209
210        return buf;
211    }
212
213
214    /**
215     * Converts an array of bytes into an array of characters representing the
216     * hexadecimal values of each byte in order. The returned array will be
217     * double the length of the passed array, as it takes two characters to
218     * represent any given byte.
219     *
220     * @param data a byte[] to convert to Hex characters
221     * @return A char[] containing hexadecimal characters
222     */
223    public static char[] encodeHex( byte[] data )
224    {
225        int l = data.length;
226
227        char[] out = new char[l << 1];
228
229        // two characters form the hex value.
230        for ( int i = 0, j = 0; i < l; i++ )
231        {
232            out[j++] = HEX_CHAR[( 0xF0 & data[i] ) >>> 4];
233            out[j++] = HEX_CHAR[0x0F & data[i]];
234        }
235
236        return out;
237    }
238}