001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.geronimo.crypto.encoders;
019
020 /**
021 * Converters for going from hex to binary and back. Note: this class assumes ASCII processing.
022 */
023 public class HexTranslator
024 implements Translator
025 {
026 private static final byte[] hexTable =
027 {
028 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
029 (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'
030 };
031
032 /**
033 * size of the output block on encoding produced by getDecodedBlockSize()
034 * bytes.
035 */
036 public int getEncodedBlockSize()
037 {
038 return 2;
039 }
040
041 public int encode(
042 byte[] in,
043 int inOff,
044 int length,
045 byte[] out,
046 int outOff)
047 {
048 for (int i = 0, j = 0; i < length; i++, j += 2)
049 {
050 out[outOff + j] = hexTable[(in[inOff] >> 4) & 0x0f];
051 out[outOff + j + 1] = hexTable[in[inOff] & 0x0f];
052
053 inOff++;
054 }
055
056 return length * 2;
057 }
058
059 /**
060 * size of the output block on decoding produced by getEncodedBlockSize()
061 * bytes.
062 */
063 public int getDecodedBlockSize()
064 {
065 return 1;
066 }
067
068 public int decode(
069 byte[] in,
070 int inOff,
071 int length,
072 byte[] out,
073 int outOff)
074 {
075 int halfLength = length / 2;
076 byte left, right;
077 for (int i = 0; i < halfLength; i++)
078 {
079 left = in[inOff + i * 2];
080 right = in[inOff + i * 2 + 1];
081
082 if (left < (byte)'a')
083 {
084 out[outOff] = (byte)((left - '0') << 4);
085 }
086 else
087 {
088 out[outOff] = (byte)((left - 'a' + 10) << 4);
089 }
090 if (right < (byte)'a')
091 {
092 out[outOff] += (byte)(right - '0');
093 }
094 else
095 {
096 out[outOff] += (byte)(right - 'a' + 10);
097 }
098
099 outOff++;
100 }
101
102 return halfLength;
103 }
104 }