KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > misc > HexEncoder


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.core.misc;
66
67 import com.jcorporate.expresso.kernel.util.FastStringBuffer;
68
69
70 /**
71  * Hex encoding class.
72  * Many thanks goes to Wei Dai's
73  * <A HREF="http://www.eskimo.com/~weidai/cryptlib.html">Crypto++</A> for providing
74  * public domain C++ code that this could be derived from.
75  *
76  * @author Michael Rimov
77  */

78 public class HexEncoder {
79
80     /**
81      * Lookup table used for encoding.
82      */

83     private static final char[] codes = {
84         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
85         'E', 'F'
86     };
87
88     private static final String JavaDoc thisClass = HexEncoder.class.getName();
89
90     public HexEncoder() {
91     }
92
93     /**
94      * A step in the decoding process.
95      *
96      * @param inChar the character to conver
97      * @return -1 if the input character is not a proper hex code. otherwise the
98      * value we need.
99      */

100     private static int convertToNumber(char inChar) {
101         if (inChar >= '0' && inChar <= '9') {
102             return inChar - '0';
103         }
104         if (inChar >= 'A' && inChar <= 'F') {
105             return inChar - 'A' + 10;
106         }
107         if (inChar >= 'a' && inChar <= 'f') {
108             return inChar - 'a' + 10;
109         }
110
111         return -1;
112     } /* convertToNumber(char) */
113
114     /**
115      * Decodes a string containing hexadecimal characters into the resulting binary
116      * values.
117      *
118      * @param inputData - The string to be decoded. The input string must have
119      * only characters "0-9 and A-F" Any other characters in the string
120      * will result in an illegal argument exception.
121      * @return an array of bytes representing the decoded input string
122      * @throws IllegalArgumentException if the string is null, is of zero length, or
123      * contains illegal characters.
124      */

125     public static byte[] decode(String JavaDoc inputData)
126             throws IllegalArgumentException JavaDoc {
127
128         //Parameter Checks
129
if (inputData == null) {
130             throw new IllegalArgumentException JavaDoc(thisClass + "decode(String)" +
131                     " inputData must not be null");
132         }
133
134         int len = inputData.length();
135
136         if (len == 0) {
137             throw new IllegalArgumentException JavaDoc(thisClass + "decode(String)" +
138                     " inputData must be of length > 0");
139         }
140         if (len % 2 != 0) {
141             throw new IllegalArgumentException JavaDoc(thisClass + "decode(String)" +
142                     " inputData must be of even length");
143         }
144
145         //The main function
146
byte[] finalResult = new byte[len / 2];
147         int temp;
148         int arrayPos = 0;
149
150         for (int i = 0; i < len; i++) {
151             temp = HexEncoder.convertToNumber(inputData.charAt(i));
152
153             if (temp < 0) {
154                 throw new IllegalArgumentException JavaDoc(thisClass + "decode(String)" +
155                         " illegal hex character in input Data: " +
156                         inputData);
157             }
158             if (i % 2 == 1) {
159                 byte temp2 = (byte) (finalResult[arrayPos] << 4);
160                 finalResult[arrayPos] = (byte) (temp2 | (byte) temp);
161                 arrayPos++;
162             } else {
163                 finalResult[arrayPos] = (byte) temp;
164             }
165         }
166
167         return finalResult;
168     } /* decode(String) */
169
170
171     /**
172      * Encode an array of binary data into a string of hexadecimal values.
173      *
174      * @param inputData - A byte array that will be encoded.
175      * @return The resulting encoded string.
176      * @throws IllegalArgumentException If the length of the byte array is zero.
177      */

178     public static String JavaDoc encode(byte[] inputData)
179             throws IllegalArgumentException JavaDoc {
180         int len = inputData.length;
181
182         if (len == 0) {
183             throw new IllegalArgumentException JavaDoc(thisClass + ".encode(byte)" +
184                     " inputData must be of length > 0");
185         }
186
187         FastStringBuffer buffer = new FastStringBuffer(len * 2);
188
189         for (int i = 0; i < len; i++) {
190             int a = inputData[i];
191
192             if (a < 0) {
193                 a = (a & 0x00FF); //Remove the sign extension
194
}
195
196             a >>>= 4;
197             buffer.append(codes[a]);
198             buffer.append(codes[inputData[i] & 0x0F]);
199         }
200
201         return buffer.toString();
202     } /* encode(byte) */
203
204
205     /**
206      * Encode an array of binary data into a string of hexadecimal values.
207      *
208      * @param s the string to encode
209      * @return The resulting encoded string.
210      * @throws IllegalArgumentException If the length of the byte array is zero.
211      */

212     public static String JavaDoc encode(String JavaDoc s)
213             throws IllegalArgumentException JavaDoc {
214         return encode(s.getBytes());
215     } /* encode(String) */
216
217
218 } /* HexEncoder */
219
220 /* HexEncoder */
Popular Tags