001 /*
002 * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.11/src/java/org/apache/commons/ssl/util/Hex.java $
003 * $Revision: 121 $
004 * $Date: 2007-11-13 21:26:57 -0800 (Tue, 13 Nov 2007) $
005 *
006 * ====================================================================
007 * Licensed to the Apache Software Foundation (ASF) under one
008 * or more contributor license agreements. See the NOTICE file
009 * distributed with this work for additional information
010 * regarding copyright ownership. The ASF licenses this file
011 * to you under the Apache License, Version 2.0 (the
012 * "License"); you may not use this file except in compliance
013 * with the License. You may obtain a copy of the License at
014 *
015 * http://www.apache.org/licenses/LICENSE-2.0
016 *
017 * Unless required by applicable law or agreed to in writing,
018 * software distributed under the License is distributed on an
019 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
020 * KIND, either express or implied. See the License for the
021 * specific language governing permissions and limitations
022 * under the License.
023 * ====================================================================
024 *
025 * This software consists of voluntary contributions made by many
026 * individuals on behalf of the Apache Software Foundation. For more
027 * information on the Apache Software Foundation, please see
028 * <http://www.apache.org/>.
029 *
030 */
031
032 package org.apache.commons.ssl.util;
033
034 /**
035 * Utility class for dealing with hex-encoding of binary data.
036 *
037 * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@gmail.com</a>
038 * @since 13-Nov-2007
039 */
040 public class Hex {
041
042 public static byte[] decode(String s) {
043 byte[] b = new byte[s.length() / 2];
044 for (int i = 0; i < b.length; i++) {
045 String hex = s.substring(2 * i, 2 * (i + 1));
046 b[i] = (byte) Integer.parseInt(hex, 16);
047 }
048 return b;
049 }
050
051 public static byte[] decode(byte[] hexString) {
052 byte[] b = new byte[hexString.length / 2];
053 char[] chars = new char[2];
054 for (int i = 0; i < b.length; i++) {
055 chars[0] = (char) hexString[2 * i];
056 chars[1] = (char) hexString[2 * i + 1];
057 String hex = new String(chars);
058 b[i] = (byte) Integer.parseInt(hex, 16);
059 }
060 return b;
061 }
062
063 public static String encode(byte[] b) {
064 return encode(b, 0, b.length);
065 }
066
067 public static String encode(byte[] b, int offset, int length) {
068 StringBuffer buf = new StringBuffer();
069 int len = Math.min(offset + length, b.length);
070 for (int i = offset; i < len; i++) {
071 int c = (int) b[i];
072 if (c < 0) {
073 c = c + 256;
074 }
075 if (c >= 0 && c <= 15) {
076 buf.append('0');
077 }
078 buf.append(Integer.toHexString(c));
079 }
080 return buf.toString();
081 }
082
083 }