001: package org.bouncycastle.util.encoders;
002:
003: import java.io.ByteArrayOutputStream;
004: import java.io.IOException;
005: import java.io.OutputStream;
006:
007: public class Hex {
008: private static final Encoder encoder = new HexEncoder();
009:
010: /**
011: * encode the input data producing a Hex encoded byte array.
012: *
013: * @return a byte array containing the Hex encoded data.
014: */
015: public static byte[] encode(byte[] data) {
016: return encode(data, 0, data.length);
017: }
018:
019: /**
020: * encode the input data producing a Hex encoded byte array.
021: *
022: * @return a byte array containing the Hex encoded data.
023: */
024: public static byte[] encode(byte[] data, int off, int length) {
025: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
026:
027: try {
028: encoder.encode(data, off, length, bOut);
029: } catch (IOException e) {
030: throw new RuntimeException(
031: "exception encoding Hex string: " + e);
032: }
033:
034: return bOut.toByteArray();
035: }
036:
037: /**
038: * Hex encode the byte data writing it to the given output stream.
039: *
040: * @return the number of bytes produced.
041: */
042: public static int encode(byte[] data, OutputStream out)
043: throws IOException {
044: return encoder.encode(data, 0, data.length, out);
045: }
046:
047: /**
048: * Hex encode the byte data writing it to the given output stream.
049: *
050: * @return the number of bytes produced.
051: */
052: public static int encode(byte[] data, int off, int length,
053: OutputStream out) throws IOException {
054: return encoder.encode(data, off, length, out);
055: }
056:
057: /**
058: * decode the Hex encoded input data. It is assumed the input data is valid.
059: *
060: * @return a byte array representing the decoded data.
061: */
062: public static byte[] decode(byte[] data) {
063: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
064:
065: try {
066: encoder.decode(data, 0, data.length, bOut);
067: } catch (IOException e) {
068: throw new RuntimeException(
069: "exception decoding Hex string: " + e);
070: }
071:
072: return bOut.toByteArray();
073: }
074:
075: /**
076: * decode the Hex encoded String data - whitespace will be ignored.
077: *
078: * @return a byte array representing the decoded data.
079: */
080: public static byte[] decode(String data) {
081: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
082:
083: try {
084: encoder.decode(data, bOut);
085: } catch (IOException e) {
086: throw new RuntimeException(
087: "exception decoding Hex string: " + e);
088: }
089:
090: return bOut.toByteArray();
091: }
092:
093: /**
094: * decode the Hex encoded String data writing it to the given output stream,
095: * whitespace characters will be ignored.
096: *
097: * @return the number of bytes produced.
098: */
099: public static int decode(String data, OutputStream out)
100: throws IOException {
101: return encoder.decode(data, out);
102: }
103: }
|