View Javadoc
1   /**
2    * Copyright 2014 Internet2
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  /*
17   * Copyright 2001-2004 The Apache Software Foundation.
18   * 
19   * Licensed under the Apache License, Version 2.0 (the "License");
20   * you may not use this file except in compliance with the License.
21   * You may obtain a copy of the License at
22   * 
23   *      http://www.apache.org/licenses/LICENSE-2.0
24   * 
25   * Unless required by applicable law or agreed to in writing, software
26   * distributed under the License is distributed on an "AS IS" BASIS,
27   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28   * See the License for the specific language governing permissions and
29   * limitations under the License.
30   */ 
31  
32  package edu.internet2.middleware.grouperClientExt.org.apache.commons.codec.binary;
33  
34  import edu.internet2.middleware.grouperClientExt.org.apache.commons.codec.BinaryDecoder;
35  import edu.internet2.middleware.grouperClientExt.org.apache.commons.codec.BinaryEncoder;
36  import edu.internet2.middleware.grouperClientExt.org.apache.commons.codec.DecoderException;
37  import edu.internet2.middleware.grouperClientExt.org.apache.commons.codec.EncoderException;
38  
39  /**
40   * Hex encoder and decoder.
41   * 
42   * @since 1.1
43   * @author Apache Software Foundation
44   * @version $Id: Hex.java,v 1.1 2008-11-30 10:57:26 mchyzer Exp $
45   */
46  public class Hex implements BinaryEncoder, BinaryDecoder {
47  
48      /** 
49       * Used building output as Hex 
50       */
51      private static final char[] DIGITS = {
52          '0', '1', '2', '3', '4', '5', '6', '7',
53             '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
54      };
55  
56      /**
57       * Converts an array of characters representing hexidecimal values into an
58       * array of bytes of those same values. The returned array will be half the
59       * length of the passed array, as it takes two characters to represent any
60       * given byte. An exception is thrown if the passed char array has an odd
61       * number of elements.
62       * 
63       * @param data An array of characters containing hexidecimal digits
64       * @return A byte array containing binary data decoded from
65       *         the supplied char array.
66       * @throws DecoderException Thrown if an odd number or illegal of characters 
67       *         is supplied
68       */
69      public static byte[] decodeHex(char[] data) throws DecoderException {
70  
71          int len = data.length;
72  
73          if ((len & 0x01) != 0) {
74              throw new DecoderException("Odd number of characters.");
75          }
76  
77          byte[] out = new byte[len >> 1];
78  
79          // two characters form the hex value.
80          for (int i = 0, j = 0; j < len; i++) {
81              int f = toDigit(data[j], j) << 4;
82              j++;
83              f = f | toDigit(data[j], j);
84              j++;
85              out[i] = (byte) (f & 0xFF);
86          }
87  
88          return out;
89      }
90  
91      /**
92       * Converts a hexadecimal character to an integer.
93       *  
94       * @param ch A character to convert to an integer digit
95       * @param index The index of the character in the source
96       * @return An integer
97       * @throws DecoderException Thrown if ch is an illegal hex character
98       */
99      protected static int toDigit(char ch, int index) throws DecoderException {
100         int digit = Character.digit(ch, 16);
101         if (digit == -1) {
102             throw new DecoderException("Illegal hexadecimal charcter " + ch + " at index " + index);
103         }
104         return digit;
105     }
106 
107     /**
108      * Converts an array of bytes into an array of characters representing the hexidecimal values of each byte in order.
109      * The returned array will be double the length of the passed array, as it takes two characters to represent any
110      * given byte.
111      * 
112      * @param data
113      *                  a byte[] to convert to Hex characters
114      * @return A char[] containing hexidecimal characters
115      */
116     public static char[] encodeHex(byte[] data) {
117 
118         int l = data.length;
119 
120            char[] out = new char[l << 1];
121 
122            // two characters form the hex value.
123            for (int i = 0, j = 0; i < l; i++) {
124                out[j++] = DIGITS[(0xF0 & data[i]) >>> 4 ];
125                out[j++] = DIGITS[ 0x0F & data[i] ];
126            }
127 
128            return out;
129     }
130 	
131     /**
132      * Converts an array of character bytes representing hexidecimal values into an
133      * array of bytes of those same values. The returned array will be half the
134      * length of the passed array, as it takes two characters to represent any
135      * given byte. An exception is thrown if the passed char array has an odd
136      * number of elements.
137      * 
138      * @param array An array of character bytes containing hexidecimal digits
139      * @return A byte array containing binary data decoded from
140      *         the supplied byte array (representing characters).
141      * @throws DecoderException Thrown if an odd number of characters is supplied
142      *                   to this function
143      * @see #decodeHex(char[])
144      */
145 	public byte[] decode(byte[] array) throws DecoderException {
146 		return decodeHex(new String(array).toCharArray());
147 	}
148 	
149     /**
150      * Converts a String or an array of character bytes representing hexidecimal values into an
151      * array of bytes of those same values. The returned array will be half the
152      * length of the passed String or array, as it takes two characters to represent any
153      * given byte. An exception is thrown if the passed char array has an odd
154      * number of elements.
155      * 
156      * @param object A String or, an array of character bytes containing hexidecimal digits
157      * @return A byte array containing binary data decoded from
158      *         the supplied byte array (representing characters).
159      * @throws DecoderException Thrown if an odd number of characters is supplied
160      *                   to this function or the object is not a String or char[]
161      * @see #decodeHex(char[])
162      */
163 	public Object decode(Object object) throws DecoderException {
164 		try {
165             char[] charArray = object instanceof String ? ((String) object).toCharArray() : (char[]) object;
166 		    return decodeHex(charArray);
167 		} catch (ClassCastException e) {
168 		    throw new DecoderException(e.getMessage());
169 		}
170 	}
171 	
172     /**
173      * Converts an array of bytes into an array of bytes for the characters representing the
174      * hexidecimal values of each byte in order. The returned array will be
175      * double the length of the passed array, as it takes two characters to
176      * represent any given byte.
177      *
178      * @param array a byte[] to convert to Hex characters
179      * @return A byte[] containing the bytes of the hexidecimal characters
180      * @see #encodeHex(byte[])
181      */
182 	public byte[] encode(byte[] array) {
183 		return new String(encodeHex(array)).getBytes();
184 	}
185 
186     /**
187      * Converts a String or an array of bytes into an array of characters representing the
188      * hexidecimal values of each byte in order. The returned array will be
189      * double the length of the passed String or array, as it takes two characters to
190      * represent any given byte.
191      *
192      * @param object a String, or byte[] to convert to Hex characters
193      * @return A char[] containing hexidecimal characters
194      * @throws EncoderException Thrown if the given object is not a String or byte[]
195      * @see #encodeHex(byte[])
196      */
197 	public Object encode(Object object) throws EncoderException {	
198 		try {
199             byte[] byteArray = object instanceof String ? ((String) object).getBytes() : (byte[]) object;
200 			return encodeHex(byteArray);
201 		} catch (ClassCastException e) {
202 			throw new EncoderException(e.getMessage());
203 		}
204 	}
205 
206 }
207