KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > maverick > crypto > encoders > Hex


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.maverick.crypto.encoders;
21
22 /**
23  * Converters for going from hex to binary and back.
24  * <p>
25  * Note: this class assumes ASCII processing.
26  */

27 public class Hex
28 {
29     private static HexTranslator encoder = new HexTranslator();
30
31     public static byte[] encode(
32         byte[] array)
33     {
34         return encode(array, 0, array.length);
35     }
36
37     public static byte[] encode(
38         byte[] array,
39         int off,
40         int length)
41     {
42         byte[] enc = new byte[length * 2];
43
44         encoder.encode(array, off, length, enc, 0);
45
46         return enc;
47     }
48
49     public static byte[] decode(
50         String JavaDoc string)
51     {
52         byte[] bytes = new byte[string.length() / 2];
53         String JavaDoc buf = string.toLowerCase();
54
55         for (int i = 0; i < buf.length(); i += 2)
56         {
57             char left = buf.charAt(i);
58             char right = buf.charAt(i+1);
59             int index = i / 2;
60
61             if (left < 'a')
62             {
63                 bytes[index] = (byte)((left - '0') << 4);
64             }
65             else
66             {
67                 bytes[index] = (byte)((left - 'a' + 10) << 4);
68             }
69             if (right < 'a')
70             {
71                 bytes[index] += (byte)(right - '0');
72             }
73             else
74             {
75                 bytes[index] += (byte)(right - 'a' + 10);
76             }
77         }
78
79         return bytes;
80     }
81
82     public static byte[] decode(
83         byte[] array)
84     {
85         byte[] bytes = new byte[array.length / 2];
86
87         encoder.decode(array, 0, array.length, bytes, 0);
88
89         return bytes;
90     }
91 }
92
Popular Tags