001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.converter.crypto;
018    
019    /**
020     * <code>HexUtils</code> provides utility methods for hex conversions
021     */
022    public final class HexUtils {
023    
024        private static char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
025    
026        private HexUtils() { }
027    
028        /**
029         * Creates a string representation of the supplied byte array in Hexidecimal
030         * format
031         *
032         * @param in the byte array to convert to a hex string.
033         * @param start where to begin in the array
034         * @param length how many bytes from the array to include in the hexidecimal
035         *            representation
036         * @return a string containing the hexidecimal representation of the
037         *         requested bytes from the array
038         */
039        public static  String byteArrayToHexString(byte in[], int start, int length) {
040            String asHexString = null;
041            if (in != null) {
042                StringBuilder out = new StringBuilder(in.length * 2);
043                for (int x = start; x < length; x++) {
044                    int nybble = in[x] & 0xF0;
045                    nybble = nybble >>> 4;
046                    out.append(hexChars[nybble]);
047                    out.append(hexChars[in[x] & 0x0F]);
048                }
049                asHexString = out.toString();
050            }
051            return asHexString;
052        }
053    
054        /**
055         * Creates a string representation of the supplied byte array in Hexidecimal
056         * format
057         *
058         * @param in the byte array to convert to a hex string.
059         * @return a string containing the hexidecimal representation of the array
060         */
061        public static  String byteArrayToHexString(byte in[]) {
062            return byteArrayToHexString(in, 0, in.length);
063        }
064    
065        /**
066         * Convert a hex string into an array of bytes. The string is expected to
067         * consist entirely of valid Hex characters i.e. 0123456789abcdefABCDEF. The
068         * array is calculated by traversing the string from from left to right,
069         * ignoring whitespace. Every 2 valid hex chars will constitute a new byte
070         * for the array. If the string is uneven then it the last byte will be
071         * padded with a '0'.
072         *
073         * @param hexString String to be converted
074         */
075        public static  byte[] hexToByteArray(String hexString) {
076    
077            StringBuilder normalize = new StringBuilder(hexString.length());
078            for (int x = 0; x < hexString.length(); x++) {
079                char current = Character.toLowerCase(hexString.charAt(x));
080                if (isHexChar(current)) {
081                    normalize.append(current);
082                } else if (!Character.isWhitespace(current)) {
083                    throw new IllegalStateException(String.format("Conversion of hex string to array failed. '%c' is not a valid hex character", current));
084                }
085            }
086            // pad with a zero if we have an uneven number of characters.
087            if (normalize.length() % 2 > 0) {
088                normalize.append('0');
089            }
090            byte[] hexArray = new byte[hexString.length() + 1 >> 1];
091            for (int x = 0; x < hexArray.length; x++) {
092                int ni = x << 1;
093    
094                int mostSignificantNybble = Character.digit(normalize.charAt(ni), 16);
095                int leastSignificantNybble = Character.digit(normalize.charAt(ni + 1), 16);
096    
097                int value = ((mostSignificantNybble << 4)) | (leastSignificantNybble & 0x0F);
098                hexArray[x] = (byte)value;
099            }
100            return hexArray;
101        }
102    
103        public static  boolean isHexChar(char current) {
104            return Character.digit(current, 16) >= 0;
105        }
106    
107    }