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 class Hex
036{
037    /** &lt;hex> ::= [0x30-0x39] | [0x41-0x46] | [0x61-0x66] */
038    public static final byte[] HEX_VALUE =
039        {
040            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00 -> 0F
041            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10 -> 1F
042            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20 -> 2F
043             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 )
044            -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 40 -> 4F ( A, B, C, D, E, F )
045            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 50 -> 5F
046            -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 60 -> 6F ( a, b, c, d, e, f )
047            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1  // 70 -> 7F
048        };
049
050    /** Used to build output as Hex */
051    public static final char[] HEX_CHAR =
052        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
053
054
055    /**
056     * Translate two chars to an hex value. The chars must be
057     * in [a-fA-F0-9]
058     *
059     * @param high The high value
060     * @param low The low value
061     * @return A byte representation of the two chars
062     */
063    public static byte getHexValue( char high, char low )
064    {
065        if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) )
066        {
067            return -1;
068        }
069
070        return ( byte ) ( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
071    }
072
073
074    /**
075     * Translate two bytes to an hex value. The bytes must be
076     * in [0-9a-fA-F]
077     *
078     * @param high The high value
079     * @param low The low value
080     * @return A byte representation of the two bytes
081     */
082    public static byte getHexValue( byte high, byte low )
083    {
084        if ( ( ( high & 0x7F ) != high ) || ( ( low & 0x7F ) != low ) )
085        {
086            return -1;
087        }
088
089        return ( byte ) ( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
090    }
091
092
093    /**
094     * Return an hex value from a single char
095     * The char must be in [0-9a-fA-F]
096     *
097     * @param c The char we want to convert
098     * @return A byte between 0 and 15
099     */
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}