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.shared.util;
021
022
023import org.apache.directory.shared.i18n.I18n;
024
025import javax.naming.InvalidNameException;
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        };
048    /** Used to build output as Hex */
049    public static final char[] HEX_CHAR =
050        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
051
052    /**
053     * Translate two chars to an hex value. The chars must be
054     * in [a-fA-F0-9]
055     *
056     * @param high The high value
057     * @param low The low value
058     * @return A byte representation of the two chars
059     */
060    public static byte getHexValue( char high, char low )
061    {
062        if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) )
063        {
064            return -1;
065        }
066
067        return (byte)( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
068    }
069
070    /**
071     * Translate two bytes to an hex value. The bytes must be
072     * in [0-9a-fA-F]
073     *
074     * @param high The high value
075     * @param low The low value
076     * @return A byte representation of the two bytes
077     */
078    public static byte getHexValue( byte high, byte low )
079    {
080        if ( ( high > 127 ) || ( low > 127 ) || ( high < 0 ) | ( low < 0 ) )
081        {
082            return -1;
083        }
084
085        return (byte)( ( HEX_VALUE[high] << 4 ) | HEX_VALUE[low] );
086    }
087
088    /**
089     * Return an hex value from a sinle char
090     * The char must be in [0-9a-fA-F]
091     *
092     * @param c The char we want to convert
093     * @return A byte between 0 and 15
094     */
095    public static byte getHexValue( char c )
096    {
097        if ( ( c > 127 ) || ( c < 0 ) )
098        {
099            return -1;
100        }
101
102        return HEX_VALUE[c];
103    }
104
105
106    /**
107     * Decodes values of attributes in the DN encoded in hex into a UTF-8
108     * String.  RFC2253 allows a DN's attribute to be encoded in hex.
109     * The encoded value starts with a # then is followed by an even
110     * number of hex characters.
111     *
112     * @param str the string to decode
113     * @return the decoded string
114     * @throws InvalidNameException
115     */
116    public static String decodeHexString( String str ) throws InvalidNameException
117    {
118        if ( str == null || str.length() == 0 )
119        {
120            throw new InvalidNameException( I18n.err( I18n.ERR_04431 ) );
121        }
122
123        char[] chars = str.toCharArray();
124
125        if ( chars[0] != '#' )
126        {
127            throw new InvalidNameException( I18n.err( I18n.ERR_04432, str ) );
128        }
129
130        // the bytes representing the encoded string of hex
131        // this should be ( length - 1 )/2 in size
132        byte[] decoded = new byte[ ( chars.length - 1 ) >> 1 ];
133
134        for ( int ii = 1, jj = 0 ; ii < chars.length; ii+=2, jj++ )
135        {
136            int ch = ( HEX_VALUE[chars[ii]] << 4 )
137                 + HEX_VALUE[chars[ii + 1]];
138            decoded[jj] = ( byte ) ch;
139        }
140
141        return Strings.utf8ToString(decoded);
142    }
143
144
145    /**
146     * Convert an escaoed list of bytes to a byte[]
147     *
148     * @param str the string containing hex escapes
149     * @return the converted byte[]
150     */
151    public static byte[] convertEscapedHex( String str ) throws InvalidNameException
152    {
153        if ( str == null )
154        {
155            throw new InvalidNameException( I18n.err( I18n.ERR_04433 ) );
156        }
157
158        int length = str.length();
159
160        if ( length == 0 )
161        {
162            throw new InvalidNameException( I18n.err( I18n.ERR_04434 ) );
163        }
164
165        // create buffer and add everything before start of scan
166        byte[] buf = new byte[ str.length()/3];
167        int pos = 0;
168
169        // start scaning until we find an escaped series of bytes
170        for ( int i = 0; i < length; i++ )
171        {
172            char c = str.charAt( i );
173
174            if ( c == '\\' )
175            {
176                // we have the start of a hex escape sequence
177                if ( Chars.isHex(str, i + 1) && Chars.isHex(str, i + 2) )
178                {
179                    byte value = ( byte ) ( ( HEX_VALUE[str.charAt( i + 1 )] << 4 )
180                        + HEX_VALUE[str.charAt( i + 2 )] );
181
182                    i+=2;
183                    buf[pos++] = value;
184                }
185            }
186            else
187            {
188                throw new InvalidNameException( I18n.err( I18n.ERR_04435 ) );
189            }
190        }
191
192        return buf;
193    }
194
195    /**
196     * Converts an array of bytes into an array of characters representing the
197     * hexidecimal values of each byte in order. The returned array will be
198     * double the length of the passed array, as it takes two characters to
199     * represent any given byte.
200     *
201     * @param data a byte[] to convert to Hex characters
202     * @return A char[] containing hexidecimal characters
203     */
204    public static char[] encodeHex( byte[] data )
205    {
206        int l = data.length;
207
208        char[] out = new char[l << 1];
209
210        // two characters form the hex value.
211        for ( int i = 0, j = 0; i < l; i++ )
212        {
213            out[j++] = HEX_CHAR[( 0xF0 & data[i] ) >>> 4];
214            out[j++] = HEX_CHAR[0x0F & data[i]];
215        }
216
217        return out;
218    }
219}