View Javadoc
1   package org.apache.fulcrum.jce.crypto;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  /**
23   * Helper class to for HEX conversion.
24   *
25   * @author <a href="mailto:painter@apache.org">Jeffery Painter</a>
26   * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl</a>
27   * @author <a href="mailto:maakus@earthlink.net">Markus Hahn</a>
28   */
29  
30  public final class HexConverter
31  {
32      /**
33       * Converts a byte array to a hex string.
34       *
35       * @param data the byte array
36       * @return the hex string
37       */
38      public static String toString( byte[] data )
39      {
40          return bytesToHexStr(data);
41      }
42  
43      /**
44       * Converts a hex string into a byte[]
45       *
46       * @param sHex the hex string
47       * @return the byte[]
48       */
49      public static byte[] toBytes(String sHex) {
50          int len = sHex.length();
51          byte[] data = new byte[len / 2];
52          for (int i = 0; i < len; i += 2) {
53              data[i / 2] = (byte) ((Character.digit(sHex.charAt(i), 16) << 4)
54                                   + Character.digit(sHex.charAt(i+1), 16));
55          }
56          return data;
57      }    
58      
59      /**
60       * Converts a byte array to a hex string.
61       * @param data the byte array
62       * @return the hex string
63       */
64      private static String bytesToHexStr( byte[] data )
65      {
66          StringBuilder sbuf = new StringBuilder();
67          for ( byte b : data )
68          	sbuf.append( String.format("%02x", b ) );
69          return sbuf.toString();
70      }
71  
72  }